react 組件通信

1.父組件向子組件通信

父組件通過props向子組件傳遞需要的信息

parent.jsx

import React, { Component } from 'react';
import Son from '../components/Test1';

class Parent extends Component{
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div className="p2s">
        <Son name="hei hei" />
      </div>
    )
  }
}

export default Parent;

child.jsx

import React, {Component} from 'react';

class Son extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
  }

  render() {
    console.log(this.props);
    return (<div className="Test1">{this.props.name}</div>);
  }
}

export default Son;

2.子組件向父組件通信

  • 利用回調函數
  • react自定義事件機制

son.jsx

import React, {Component} from 'react';

class Son extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
  }

  render() {
    console.log(this.props);
    console.log(typeof this.props.hideComponent)
    return (<button className="Test2" onClick={this.props.hideComponent}>隱藏</button>);
  }
}

export default Son;

parent.jsx

import React, { Component } from 'react';
import Son from '../components/Test2';

class Home extends Component{
  constructor(props) {
    super(props);
    this.state = {
      isShow: true
    }
  }
  showComponent() {
    this.setState({
      isShow: true
    })
  }
  hideComponent() {
    this.setState({
      isShow: false
    })
  }
  render() {
    return (
      <div className="s2p" style={{textAlign: 'center', marginTop: '100px'}}>
        <button onClick={this.showComponent.bind(this)}>顯示</button>
        <Son hideComponent={this.hideComponent.bind(this)} />
        {
          this.state.isShow?(<h1>hh</h1>):''
        }
      </div>
    )
  }
}

export default Home;

3.跨組件通信

跨組件通信一般有兩種方式:
1. 中間組件層層傳遞props
2. 使用context對象

第一種props傳遞方式,組件嵌套過深時,不推薦使用
第二種context方式,context就相當於一個全局變量,這樣通信就很方便了

context通信使用方式:
1.上級組件要聲明context,並提供一個函數返回相應的context對象
2.子組件使用context,需要聲明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章