React/組件通訊

組件通訊能夠分爲如下幾種:javascript

  • 父組件向子組件通訊
  • 子組件向父組件通訊
  • 跨級組件的通訊及context
  • 沒有嵌套關係的組件通訊

 

父組件向子組件通訊
 
父組件經過props向子組件傳遞須要的信息。
 
子組件向父組件通訊

 

子組件調用porp中傳來的父組件的方法達到通訊的目的java

 

跨級組件的通訊ide

Context 提供了一個無需爲每層組件手動添加 props,就能在組件樹間進行數據傳遞的方法。this

 

// Context 能夠讓咱們無須明確地傳遍每個組件,就能將值深刻傳遞進組件樹。
// 爲當前的 theme 建立一個 context(「light」爲默認值)。
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // 使用一個 Provider 來將當前的 theme 傳遞給如下的組件樹。
    // 不管多深,任何組件都能讀取這個值。
    // 在這個例子中,咱們將 「dark」 做爲當前的值傳遞下去。
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// 中間的組件不再必指明往下傳遞 theme 了。
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  // 指定 contextType 讀取當前的 theme context。
  // React 會往上找到最近的 theme Provider,而後使用它的值。
  // 在這個例子中,當前的 theme 值爲 「dark」。
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

  

沒有嵌套關係的組件通訊spa

使用events庫,收信方在componentDidMount裏面註冊監聽事件,在componentUnMount裏銷燬該事件。發信方則使用emit方法便可發出通信消息。(切記,有註冊,就得有銷燬component

// 使用示例
class List1 extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            text: 'list1'
        }
    }
    render() {
        return (
            <div>{ this.state.text }</div>
        )
    }
    componentDidMount() {
        this.eventEmitter = ee.addListener('changeMessage', (msg) => {
            this.setState({
                text: msg
            })
        })
    }
    componentWillUnmount() {
        ee.removeListener(this.eventEmitter)
    }
}
class List2 extends React.Component{
    handleClick(message) {
        ee.emit('changeMessage', message)
    }
    render() {
        return (
            <button onClick={ this.handleClick.bind(this, '哈哈')}>點點點</button>
        )
    }
}
相關文章
相關標籤/搜索