組件傳參

基礎(chǔ)傳參props
傳數(shù)據(jù)
<Child age={this.state.age}>
在子組件中
this.props.age獲取數(shù)據(jù)
傳方法
setAge=v=>this.setState({age:v})<Child age = {this.state.age} setAge={this.setAge.bind(this)}>
在子組件使用
<h3 onClick={()=>this.props.setAget(15)}>`

上下文傳參context
特點(diǎn):引入context數(shù)據(jù),實(shí)時(shí)更新,當(dāng)一個(gè)數(shù)據(jù)發(fā)生改變,所有引入數(shù)據(jù)的視圖都會(huì)發(fā)生改變

【父組件】
1.導(dǎo)入類型檢測(cè)
import PropTypes from 'prop-types'`
2.定義導(dǎo)出的數(shù)據(jù)類型
static childContextTypes ={
color:PropTypes.string,
setColor:PropTypes.func,

3.獲取需要傳參的內(nèi)容
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>
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.導(dǎo)入
import {Provider} from './context' //導(dǎo)入供應(yīng)商組件
2.用provider包裹子元素,并傳遞value數(shù)據(jù)
<Provider
value={{num:this.state.num,
setNum:this.setNum}}>
</Provider>

【子組件】
1.導(dǎo)入
import {Consumer} from './context' //導(dǎo)入消費(fèi)者組件
2.Consumer中的context獲取數(shù)據(jù)

redux react-redux 全局?jǐn)?shù)據(jù)狀態(tài)共享

1.安裝
npm i redux react-redux
2.從react-redux導(dǎo)入Provider
import {Provider} from 'react-redux'
3.把根組件替換為:
<Provuder>
<App/>
</Provuder>
4.在Provuder中添加數(shù)據(jù)倉(cāng)庫(kù)
<Provuder 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)出組件

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容