引入
本來我是沒想過總結這些東西的,會感覺比較入門。但是之前同學去騰訊面試問到了這個問題(react或vue的組件通信),我幫他整理,順便寫demo的過程中,會有一些新的體會,多總結還是有利于進步的呀。
父子組件
父 → 子
parent組件傳給child組件,符合react的單向數據流理念,自上到下傳遞props。
// 父組件class Parent extends Component { constructor() { super(); this.state = { value: '', } } handleChange = e => { this.value = e.target.value; } handleClick = () => { this.setState({ value: this.value, }) } render() { return ( <div> 我是parent <input onChange={this.handleChange} /> <div className="button" onClick={this.handleClick}>通知</div> <div> <Child value={this.state.value} /> </div> </div> ); }}// 子組件class Child extends Component { render() { const { value } = this.props; return ( <div> 我是Child,得到傳下來的值:{value} </div> ); }}父組件做的就是定義好 state ,定義好事件函數,input onChange 的時候,去緩存 value 值,然后點擊 button 的時候,改變 state , 子組件只負責展示 value 。
子 → 父
child 組件通知 parent 組件, 主要是依靠 parent 傳下來的 callback 函數執行,改變 parent 組件的狀態,或者把 child 自己的 state 通知 parent 。分兩種情況:
state 定義在 parent 組件
// parentclass Parent extends Component { constructor() { super(); this.state = { value: '', } } setValue = value => { this.setState({ value, }) } render() { return ( <div> <div>我是parent, Value是:{this.state.value}</div> <Child setValue={this.setValue} /> </div> ); }}class Child extends Component { handleChange = e => { this.value = e.target.value; } handleClick = () => { const { setValue } = this.props; setValue(this.value); } render() { return ( <div> 我是Child <div className="card"> state 定義在 parent <input onChange={this.handleChange} /> <div className="button" onClick={this.handleClick}>通知</div> </div> </div> ); }}parent 組件把改變 state 的 setValue 函數傳給 child ,child 組件自己處理內部的狀態(這里是表單的value值),當 child 組件分發消息的時候, 執行 parent 的 setValue 函數,從而改變了 parent 的 state,state發生變化, parent 組件執行 re-render 。
state 定義在 child 組件
// parentclass Parent extends Component { onChange = value => { console.log(value, '來自 child 的 value 變化'); } render() { return ( <div> <div>我是parent <Child onChange={this.onChange} /> </div> ); }}
新聞熱點
疑難解答
圖片精選