简体   繁体   English

ReactJs如何在组件之间传递数据

[英]ReactJs how to pass data between components

I'v e been learning react and am slowing developing an understanding for how to pass data between components. 我一直在学习反应,并且正在逐渐加深对如何在组件之间传递数据的理解。 On a simplify basis there seems to be 4 cases: 简单来说,似乎有4种情况:

  1. In parent pass data to child => use props 在给孩子的父级传递数据中=>使用道具
  2. In parent retrieve data from child => use ref and pass a function down 在父级中从子级中检索数据=>使用ref并向下传递一个函数
  3. In child pass data to parent => pass a function down 在子代中将数据传递给父代=>向下传递一个函数
  4. In child retrieve data from parent 在子级中从父级检索数据

It's the 4th case I haven't found any guidance on yet. 这是我还没有找到任何指导的第四种情况。 You're in a child and want to get some data from the parent that wasn't pass down as a prop. 您在一个孩子中,想从父母那里获取一些没有作为道具传递的数据。 Can that ever happen? 那会发生吗?

In addition to context , you can also get data from a parent with a callback 除了context ,您还可以通过回调从父级获取数据

class Parent extends React.Component {
  render() {
    return <Child update={Math.random} />
  }
}

class Child extends React.Component {
  state = { }

  componentDidMount() {
    this.updateState()
  }

  updateState = () => {
    const { update } = this.props
    this.setState({ something: update() }, () => {
      setTimeout(this.updateState, 1000)
    })
  }

  render() {
    return <div>{this.state.something}</div>
  }
}

the one downside to this is that the child has to explicitly request data from the parent (changing the data in the parent will not update the child like it would with context). 这样做的一个缺点是,子级必须显式地从父级请求数据(在父级中更改数据不会像在上下文中那样更新子级)。

Another way to do this is with a global store like redux. 另一种方法是使用像redux这样的全局商店。

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child />
        <button onClick={ () => this.props.setSomething(Math.random()) }>click me</button>
      </div>
    )
  }
}

// where setSomething is an action creator that changes `globalState.something`
connect(function (state) {
  return { something: state.something }
}, { setSomething })(Child)

class Child extends React.Component {
  render() {
    return <div>{ this.props.something }</div>
  }
}

connect(function (state) {
  return { something: state.something }
})(Child)

1st and 4th case are more or less the same except the case when child component pull the data from parent rather than data pushed by parent. 第一种情况和第四种情况大致相同,除了子组件从父级提取数据而不是从父级推送数据的情况。 I am not able to think the in which context it will be useful. 我无法考虑在哪种情况下它会有用。 It seems to be very unlikely situation. 这似乎是极不可能的情况。 Even if we want to achieve it then one way would be to attach a hook using functions. 即使我们想要实现它,一种方法是使用函数来附加一个钩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM