1. 程式人生 > >React:快速上手(2)——組件通信

React:快速上手(2)——組件通信

targe sta truct sets mage render 數據 super rop

React:快速上手(2)——組件通信

向父組件傳遞數據

  父組件可以通過設置子組件的props屬性進行向子組件傳值,同時也可以傳遞一個回調函數,來獲取到子組件內部的數據。

效果演示

  子組件是輸入框,父組件及時獲取到輸入框內容然後更新右邊標簽。

  技術分享圖片

父組件傳遞回調函數

父組件傳遞一個方法,即updateSpan,用於更新span內容。

class Father extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            spantxt:null
        }
    }
    /**
     * 更新span中的內容
     * @param {*} txt 
     */
    updateSpan(txt){
        this.setState({
            spantxt:txt
        })
    }
    render(){
        return(
            <div>
                <Son value=‘1‘ onChangeHandle={this.updateSpan.bind(this)}/>
                <span>{this.state.spantxt}</span>
            </div>
        )
    }
}

子組件綁定事件

  子組件綁定onChange觸發事件txtChange,當內容發生改變txtChange會設置state,同時通過訪問prop.onChangeHandle調用了父組件的updateSpan方法,此時參數值即數據就被父組件獲取到。

class Son extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            txt:props.value
        }
    }
    render(){
        return(
            <input value={this.state.txt} onChange={this.txtChange.bind(this)}/>
        )
    }
    txtChange(event){
        this.setState(
            {txt:event.target.value}
        )
        this.props.onChangeHandle(event.target.value);
    }
}

  

React:快速上手(2)——組件通信