组件传递的方式有很多种,根据传送者和接收者可以分为如下:

  • 父组件向子组件传递
  • 子组件向父组件传递
  • 兄弟组件之间的通信
  • 父组件向后代组件传递
  • 非关系组件传递

    父组件向子组件传递

    ```javascript function EmailInput(props) { return ( ); }

const element = ;

  1. <a name="zqfs4"></a>
  2. ### 子组件向父组件传递
  3. 子组件向父组件通信的基本思路是,父组件向子组件传一个函数,然后通过这个函数的回调,拿到子组件传过来的值
  4. 父组件对应代码如下:
  5. ```javascript
  6. class Parents extends Component {
  7. constructor() {
  8. super();
  9. this.state = {
  10. price: 0
  11. };
  12. }
  13. getItemPrice(e) {
  14. this.setState({
  15. price: e
  16. });
  17. }
  18. render() {
  19. return (
  20. <div>
  21. <div>price: {this.state.price}</div>
  22. {/* 向子组件中传入一个函数 */}
  23. <Child getPrice={this.getItemPrice.bind(this)} />
  24. </div>
  25. );
  26. }
  27. }

子组件代码:

  1. class Child extends Component {
  2. clickGoods(e) {
  3. // 在此函数中传入值
  4. this.props.getPrice(e);
  5. }
  6. render() {
  7. return (
  8. <div>
  9. <button onClick={this.clickGoods.bind(this, 100)}>goods1</button>
  10. <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button>
  11. </div>
  12. );
  13. }
  14. }

兄弟组件之间的通信

如果是兄弟组件之间的传递,则父组件作为中间层来实现数据的互通,通过使用父组件传递

  1. class Parent extends React.Component {
  2. constructor(props) {
  3. super(props)
  4. this.state = {count: 0}
  5. }
  6. setCount = () => {
  7. this.setState({count: this.state.count + 1})
  8. }
  9. render() {
  10. return (
  11. <div>
  12. <SiblingA
  13. count={this.state.count}
  14. />
  15. <SiblingB
  16. onClick={this.setCount}
  17. />
  18. </div>
  19. );
  20. }
  21. }

父组件向后代组件传递

父组件向后代组件传递数据是一件最普通的事情,就像全局数据一样
使用context提供了组件之间通讯的一种方式,可以共享数据,其他数据都能读取对应的数据
通过使用React.createContext创建一个context

  1. const PriceContext = React.createContext('price')

context创建成功后,其下存在Provider组件用于创建数据源,Consumer组件用于接收数据,使用实例如下:
Provider组件通过value属性用于给后代组件传递数据:

  1. <PriceContext.Provider value={100}>
  2. </PriceContext.Provider>

如果想要获取Provider传递的数据,可以通过Consumer组件或者或者使用contextType属性接收,对应分别如
下:

  1. class MyClass extends React.Component {
  2. static contextType = PriceContext;
  3. render() {
  4. let price = this.context;
  5. /* 基于这个值进行渲染工作 */
  6. }
  7. }

Consumer组件:

  1. <PriceContext.Consumer>
  2. { /*这里是一个函数*/ }
  3. {
  4. price => <div>price:{price}</div>
  5. }
  6. </PriceContext.Consumer>

非关系组件传递

如果组件之间关系类型比较复杂的情况,建议将数据进行一个全局资源管理,从而实现通信,例如redux

总结

由于React是单向数据流,主要思想是组件不会改变接收的数据,只会监听数据的变化,当数据发生变化时它们会使用接收到的新值,而不是去修改已有的值
因此,可以看到通信过程中,数据的存储位置都是存放在上级位置中