概念上,組件是封閉的環(huán)境。React中是單向數(shù)據(jù)流的設(shè)計(jì),也就是是說只有父組件傳遞資料給子組件這回事。以正確的技術(shù)說明,擁有者組件可以設(shè)置被擁有者組件中的數(shù)據(jù)。
那么子組件要如何與父組件溝通這件事,簡(jiǎn)單的來說,是一種迂回的作法,在父組件中設(shè)置了一個(gè)方法(函數(shù)),然后傳遞給子組件的props,子組件在事件觸發(fā)時(shí),直接呼叫這個(gè)props所設(shè)置的方法(函數(shù))。但這中間,有誰(對(duì)象)呼叫了函數(shù)的設(shè)置,也就是this的作用。
父組件到子組件用props設(shè)置,子組件到父組件用上面說的方式,這是基本的套路,但它只適用于簡(jiǎn)單的組件結(jié)構(gòu),因?yàn)樗喈?dāng)麻煩,而且不靈活。那么如果要作到子組件與子組件要彼此溝通這件事,就不是太容易。當(dāng)然,我想你已經(jīng)聽過,復(fù)雜的應(yīng)用需要額外使用flux或redux來解決這問題,這是必經(jīng)之路。
不過,在思考整體的React應(yīng)用設(shè)計(jì)時(shí),要有應(yīng)用領(lǐng)域狀態(tài),也就是全局狀態(tài)的概念。第一是應(yīng)用領(lǐng)域state(狀態(tài))的,通常會(huì)在父組件中,而不是子組件中,子組件有可能很多,位于樹狀結(jié)構(gòu)很深的地方。
例子:
子組件
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),是個(gè)函數(shù),呼叫它把price交給父組件中的函數(shù)去處理 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;以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注