基礎傳參props
傳數據
<Child age={this.state.age}>
在子組件中
this.props.age
獲取數據
傳方法
setAge=v=>this.setState({age:v})<Child age = {this.state.age} setAge={this.setAge.bind(this)}>
在子組件使用
<h3 onClick={()=>this.props.setAget(15)}>`
上下文傳參context
特點:引入context數據反浓,實時更新偿枕,當一個數據發(fā)生改變,所有引入數據的視圖都會發(fā)生改變
【父組件】
1.導入類型檢測
import PropTypes from 'prop-types'`
2.定義導出的數據類型
static childContextTypes ={
color:PropTypes.string,
setColor:PropTypes.func,
3.獲取需要傳參的內容
getChildContext(){
return {
color:this.state.color,
setColor:v=>this.setState({color:v})
}
}
【子孫組件】
1.定義上下文數據
static contextTypes = {
color:PropTypes.string,//字符串顏色類型
setColor:PropTypes.func,//方法類型
}
2.使用上下文數據
<h3 style={{color:this.context.color}}>Child組件</h3>
3.使用上下文方法
<Button onClick={()=>this.context.setColor('gold')}>變金色</Button>
上下文方式傳遞(context provider consumer)
【定義組件】
1.定義上下文組件
import React, { Component } from 'react';
let {Consumer,Provider} = React.createContext();
export {Consumer,Provider};
【父組件】
1.導入
import {Provider} from './context' //導入供應商組件
2.用provider包裹子元素,并傳遞value數據
<Provider
value={{num:this.state.num,
setNum:this.setNum}}>
</Provider>
【子組件】
1.導入
import {Consumer} from './context' //導入消費者組件
2.Consumer中的context獲取數據
redux react-redux 全局數據狀態(tài)共享
1.安裝
npm i redux react-redux
2.從react-redux導入Provider
import {Provider} from 'react-redux'
3.把根組件替換為:
<Provuder>
<App/>
</Provuder>
4.在Provuder中添加數據倉庫
<Provuder store={store}>
5.編寫store倉庫鲸睛,并導入倉庫
6.編寫store
①.redux導入;
②.reducer初始數據方法
③.actions處理數據動作
④.導出倉庫
7.在組件中使用
①.導入鏈接
②.導出組件