概念上,組件是封閉的環境。React中是單向數據流的設計,也就是是說只有父組件傳遞資料給子組件這回事。以正確的技術說明,擁有者組件可以設置被擁有者組件中的數據。
那么子組件要如何與父組件溝通這件事,簡單的來說,是一種迂回的作法,在父組件中設置了一個方法(函數),然后傳遞給子組件的props,子組件在事件觸發時,直接呼叫這個props所設置的方法(函數)。但這中間,有誰(對象)呼叫了函數的設置,也就是this的作用。
父組件到子組件用props設置,子組件到父組件用上面說的方式,這是基本的套路,但它只適用于簡單的組件結構,因為它相當麻煩,而且不靈活。那么如果要作到子組件與子組件要彼此溝通這件事,就不是太容易。當然,我想你已經聽過,復雜的應用需要額外使用flux或redux來解決這問題,這是必經之路。
不過,在思考整體的React應用設計時,要有應用領域狀態,也就是全局狀態的概念。第一是應用領域state(狀態)的,通常會在父組件中,而不是子組件中,子組件有可能很多,位于樹狀結構很深的地方。
例子:
子組件
import React, { Component } from 'react' export default class Item extends Component { constructor(props) { super(props) this.state = { prices: 0 } } handleChange(){ const prices =800; this.setState({ prices: price }) //用傳過來的changePrice屬性(props),是個函數,呼叫它把price交給父組件中的函數去處理 this.props.changePrice(price) } render() { const { prices } = this.state; return ( <div> <div onChange={this.handleChange.bind(this)}> </div> <p>{prices}</p> </div> ) } }
父組件
import React, { Component } from 'react'; import Item from './Item' class App extends Component { constructor(props) { super(props) this.state = {price: 0} } //給子組件用來傳price用的方法 changePrice(price){ this.setState({price: price}) } render() { return ( <div> <Item changePrice={this.changePrice.bind(this)}/> <p>{this.state.price}</p> </div> ); } } export default App;
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com