日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React組件通信

作者:想學好前端的小寶 更新時間: 2022-08-19 編程語言

組件通信

組件間是相互隔離的,若需要用到外部組件數據,就必須使用組件間通信來傳輸數據

  • 組件通信方法

  • 父組件-->子組件

    • 父組件提供要傳遞的 state 數據

    • 給子組件標簽添加屬性,值就是 state 數據

    • 子組件使用 props 進行數據的接收

class Parent extends React.Component{
  state = {
    name : 'Jack'
  }
  render() {
    return (
      <div>
        <App name={this.state.name}/>
      </div>
    )
  }
}
// 子組件使用 props 接收數據
  • 子組件--> 父組件

    思路:父組件提供一個回調函數,子組件調用,將要傳遞的數據作為回調函數的參數傳遞到父組件

    • 父組件提供回調函數

    • 將回調函數作為屬性值,傳遞給子組件

    • 子組件通過 props 調用回調函數

    • 將子組件要傳遞的數據作為參數傳遞給回調函數

// 父組件傳遞數據
class Parent extends React.Component{
  state = {
    message : ''
  }
  getChild = (msg) => {
    this.setState({
      message : msg
    })
  }
  render() {
    return (
      <div>
        <Child getMsg={this.getChild}/>
        <h1>{this.state.message}</h1>
      </div>
    )
  }
}

// 子組件使用 props 接收數據
class Child extends React.Component{
  state = { name : 'Tom'}
  handleClick = () => {
    this.props.getMsg(this.state.name)
  }
  render() {
    return (
      <button onClick={this.handleClick}>點我傳送數據</button>
    )
  }
}
  • 兄弟組件之間

    將數據傳送到最近的公共父組件中,然后由公共父組件進行管理

    需要通信的子組件使用 props 接收狀態或操作狀態

    // 公共父組件
    class Parent extends React.Component{
      // 狀態共享
      state = {
        count : 0
      }
      // 修改數據
      onChange = () => {
        this.setState({
          count : this.state.count + 1
        })
      }
      render() {
        return (
          <div>
            <Child1 count = {this.state.count} />
            <Child2 onChange = {this.onChange}/>
          </div>
        )
      }
    }
    
    const Child1 = props => {
      return <h1>計數器:{props.count}</h1>
    }
    
    const Child2 = props => {
      return <button onClick={() => props.onChange()}>+1</button>
    }
    
    ReactDOM.render(<Parent />, document.getElementById('root'))
  • 跨組件通信

    • 調用 React.createContext() 創建 Provider (提供數據) 和 Consumer(消費數據) 兩個組件

    • 使用 Provider 組件作為父節點

    • 在 Provider 組件中設置一個 value 屬性,表示需要傳輸的數據

<Provider value="xxx">
    ...
</Provider>
  • 調用 Consumer 組件接收數據

    <Consumer>
      {data => <h1>{data}</h1>}
    </Consumer>

原文鏈接:https://blog.csdn.net/weixin_51642358/article/details/126375542

欄目分類
最近更新