React元件通訊技巧

2021-09-07 12:33:06 字數 1161 閱讀 1129

1.父向子通訊

//number只是個例子

let _number = this.state.number

需要注意,_number 可以為普通引數、this.*** 引數、也可以是 this.state.*** 引數,其中this.state.***引數若發生改變,會導致 child 重新渲染

2.子向父通訊
//從父元件接函式

childtoparent() ) } let _childtoparent = this.childtoparent.bind(this)

//子元件觸發函式 let _childtoparent = this.childtoparent.bind(this) 子向父通訊

同樣,可以修改父元件的 this.state.***( this.setstate() 觸發渲染),也可以修改this.***等值

3.通用元件通訊方式(包括兄弟元件)
//建議將event相關單獨封裝模組使用

export var events = export var sendevent = (eventname, params) => export var catchevent = (eventname, callback) => export var removecatch = (eventname, callback) => 傳送元件 import from './event' brother向sister通訊

brothertosister() sendevent(events.bts, _obj) } 接收元件 import from './event' constructor() //防止多次引用 this._brothertosister = this.brothertosister.bind(this) } componentdidmount() componentwillunmount() brothertosister(e) ) }

React元件通訊技巧

communication.gif 1.父向子通訊 number只是個例子 let number this.state.number 需要注意,number 可以為普通引數 this.引數 也可以是 this.state.引數,其中this.state.引數若發生改變,會導致 child 重新渲染 ...

react 元件通訊

父元件通過props向子元件傳遞需要的資訊 parent.jsximport react,from react import son from components test1 class parent extends component render export default parent c...

React元件通訊

分類 父子元件通訊 無論父元件傳遞是props還是state,子元件都是通過props接收 子父元件通訊 父元件傳遞方法給子元件,子元件呼叫父元件傳遞過來的方法 注意 自己的狀態自己更改 非父子元件通訊 ref鏈 1.ref this.refs.2.ref this.推薦 跨元件通訊 context...