基本傳參props
子組件
傳遞數(shù)據(jù)<child age={this.state.age}>
獲取數(shù)據(jù)this.props.age
傳方法 setAage = v =>this.setState({age:v})
<child age={this.state.age} setAge={this.setAge.bind(this)}>
在子組件使用<h3 onClick={()=>this.props.setAge(15)}>
父組件
1. 導(dǎo)入類型檢測(cè)
import PropTypes from 'prop-types';
2. 定義導(dǎo)出的數(shù)據(jù)類型
static childContextTypes = {
color:PropTypes.string, // 字符串類型
setColor:PropTypes.func,// 方法類型
}
3. 獲取需要傳參的數(shù)據(jù)
getChildContext(){
return {
color:this.state.color,
setColor:v=>this.setState({color:v})}
}
子孫組件
1. 定義上下文數(shù)據(jù)類型
static contextTypes = {
color:PropTypes.string, // 字符串類型
setColor:PropTypes.func,// 方法類型
}
2. 使用上下文數(shù)據(jù)
<h3 style={{color:this.context.color}}>Child組件</h3>
使用上下文方法
<button onClick={()=>this.context.setColor('gold')}>
context provider Comsumer 上下文方式傳遞
1. 定義 上下文組件
import React from 'react'
let { Consumer, Provider } = React.createContext();
// 創(chuàng)建一個(gè)上下文 結(jié)構(gòu) Consumer 消費(fèi)者, Provider 供應(yīng)商
export { Consumer, Provider }
// 導(dǎo)出
2. 父組件
導(dǎo)入
import {Provider} from './context'
用provider包裹子元素 并傳遞value數(shù)據(jù)
<Provider value={{
num:this.state.num,
setNum:this.setNum
}}>
3. 子組件中
導(dǎo)入
import { Consumer} from './context'
// 導(dǎo)入消費(fèi)者組件
Comsumer中的context 獲取數(shù)據(jù)
<Consumer>
{ context=>( <div> <h3> <button onClick={()=>context.setNum(context.num+1)}>{context.num}</button></h3> </div> ) }
</Consumer>
redux react-redux全局?jǐn)?shù)據(jù)狀態(tài)共享(vuex就是有參考redux的)
1 安裝
npm i redux react-redux
2. 從 react-redux導(dǎo)入Provider
import {Provider} from 'react-redux';
3. 把根組件替換為
<Provider>
<App/>
</Provider>
4. 在Provider中添加數(shù)據(jù)倉(cāng)庫(kù)
<Provider store={store}>
5. 編寫(xiě)store倉(cāng)庫(kù)并導(dǎo)入倉(cāng)庫(kù)
6.編寫(xiě)store
redux導(dǎo)入
reducer 初始數(shù)據(jù)方法
actions 處理數(shù)據(jù)動(dòng)作
導(dǎo)出倉(cāng)庫(kù)
7.在組件中使用
導(dǎo)入連接
導(dǎo)出組件
export default connect(mapStateToProps,mapDisPatchToProps)(Detail)
mapStateToProps 組state數(shù)據(jù)映射為 組件的props
mapDisPatchToProps 把state中的方法映射porps中的方法