前言
從官網上也有介紹組件間如何通信,但不夠詳細,這里做個小結,方便對比和回顧
本文內容
處理組件之間的通信, 主要取決于組件之間的關系,因此我們劃分為以下三種:
一、「父組件」向「子組件」傳值
這是最普遍的用法,實現上也非常簡單,主要是利用props來實現
// 父組件import React from 'react';import Son from './components/son';class Father extends React.Component { constructor(props) { // 這里要加super,否則會報錯 super(props); this.state = { checked: true } } render() { return ( <Son text="Toggle me" checked={this.state.checked} /> ) }}// 子組件class Son extends React.Component { render() { // 接收來自父組件的參數 let checked = this.props.checked, text = this.props.text; return ( <label>{text}: <input type="checkbox" checked={checked} /></label> ) }}多想一點:
如果組件的嵌套層次太多,那么從外到內的交流成本就會加深,通過 props 傳值的優勢就不明顯,因此,我們還是要盡可能的編寫結構清晰簡單的組件關系, 既也要遵循組件獨立原則,又要適當控制頁面,不可能或極少可能會被單用的代碼片,可不編寫成一個子組件
二、「子組件」向「父組件」傳值
我們知道,react的數據控制分為兩種,為 props 和 state;其中,props 如上剛介紹過,它是父組件向子組件傳值時作為保存參數的數據對象;而 state 是組件存放自身數據的數據對象。這兩者最主要的區別就是,props屬于父組件傳給子組件的只讀數據,在子組件中不能被修改,而state在自身組件中使用時,可以通過setState來修改更新。
子組件向父組件傳值,需要控制自己的state,并發起父組件的事件回調來通知父組件
// 父組件import Son from './components/son';class Father extends React.Component { constructor(props) { super(props) this.state = { checked: false } } onChildChanged() { this.setState({ checked: newState }) } render() { let isChecked = this.state.checked ? 'yes' : 'no'; return ( <div> <span>Are you checked: {isChecked }</span> <Son text="Toggle me" initialChecked={this.state.checked} callbackParent={this.onChildChanged.bind(this)} ></Son> </div> ) }}// 子組件class Son extends React.Component { constructor(props) { super(props); this.state = { checked: this.props.initialChecked } } onTextChange() { let newState = !this.state.check.checked; this.setState({ checked: newState }); // 注意,setState 是一個異步方法,state值不會立即改變,回調時要傳緩存的當前值, // 也可以利用傳遞一個函數(以上傳的是對象),并傳遞prevState參數來實現數據的同步更新 this.props.callbackParent(newState); } render() { let text= this.props.text; let checked = this.state.checked; return ( <label>{text}: <input type="checkbox" checked={checked} onChange={this.onTextChange.bind(this)}></label> ) }}
新聞熱點
疑難解答
圖片精選