组件、组件通信 
- 函数式创建
- 通过 React.createClass 方法创建
- 继承 React.Component 创建
通信 
- 父组件向子组件传递
- 子组件向父组件传递
- 兄弟组件之间的通信
- 父组件向后代组件传递
- 非关系组件传递
父组件向子组件传递 
jsx
function EmailInput(props) {
  return (
    <label>
      Email: <input value={props.email} />
    </label>
  );
}
const element = <EmailInput email="123124132@163.com" />;1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
子组件向父组件传递 
父组件向子组件传一个函数,然后通过这个函数的回调,拿到子组件传过来的值
jsx
// Parents.jsx
class Parents extends Component {
  constructor() {
    super();
    this.state = {
      price: 0,
    };
  }
  getItemPrice(e) {
    this.setState({
      price: e,
    });
  }
  render() {
    return (
      <div>
        <div>price: {this.state.price}</div>
        {/* 向子组件中传入一个函数  */}
        <Child getPrice={this.getItemPrice.bind(this)} />
      </div>
    );
  }
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
jsx
//children.jsx
class Child extends Component {
  clickGoods(e) {
    // 在此函数中传入值
    this.props.getPrice(e);
  }
  render() {
    return (
      <div>
        <button onClick={this.clickGoods.bind(this, 100)}>goods1</button>
        <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button>
      </div>
    );
  }
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
兄弟组件之间的通信 
则父组件作为中间层来实现数据的互通,通过使用父组件传递
jsx
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  setCount = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    return (
      <div>
        <SiblingA count={this.state.count} />
        <SiblingB onClick={this.setCount} />
      </div>
    );
  }
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
父组件向后代组件传递 
通过使用 React.createContext 创建一个 context
jsx
const PriceContext = React.createContext("price");1
context 创建成功后,其下存在 Provider 组件用于创建数据源, Consumer 组件用于接收数据,使用实例如下:
Provider 组件通过 value 属性用于给后代组件传递数据:
jsx
<PriceContext.Provider value={100}></PriceContext.Provider>1
如果想要获取 Provider 传递的数据,可以通过 Consumer 组件或者或者使用 contextType 属性接收,对应分别如下:
jsx
class MyClass extends React.Component {
  static contextType = PriceContext;
  render() {
    let price = this.context;
    /* 基于这个值进行渲染工作 */
  }
}1
2
3
4
5
6
7
2
3
4
5
6
7
Consumer 组件:
jsx
<PriceContext.Consumer>
  {/*这里是一个函数*/}
  {(price) => <div>price:{price}</div>}
</PriceContext.Consumer>1
2
3
4
2
3
4