【问题标题】:Pass the data from one component to another component (not a child)?将数据从一个组件传递到另一个组件(不是子组件)?
【发布时间】:2020-05-02 13:09:40
【问题描述】:

我想将数据(点击时)从一个组件 (A) 传递到另一个组件 (B),但 A 不是 B 的子级。

假设有一个表单组件(A),我们要填写必填字段,点击继续按钮后,我们想在下一个组件(B)中显示所有值。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您可以使用 React Portals,它允许在应用程序 dom 中的任何位置渲染组件,并且您可以从控制组件传递道具。

    阅读文档 https://reactjs.org/docs/portals.html

    render() {
      // React does *not* create a new div. It renders the children into `domNode`.
      // `domNode` is any valid DOM node, regardless of its location in the DOM.
      return ReactDOM.createPortal(
        <YourComponent prop1={value1} prop2={value2}/>,
        domNode
      );
    }

    【讨论】:

      【解决方案2】:

      您可以使用react-router-dom 中的Link 来传递数据。

      <Link
        to={{
          pathname: "/courses",
          state: { fromDashboard: true }
        }}
      />
      

      在上面的代码中,state 对象可以在history 对象中访问,该对象可以从useHistory 钩子从react-router-dom 导入。

      【讨论】:

        【解决方案3】:

        您可以使用 react context API 或 redux 在组件之间共享状态。

        或者,如果您只想在导航时传递数据,您可以使用history.push 函数并在状态对象中传递数据,如下所示

        history.push({pathname: 'yourlocation', state: { data: your data}})
        

        您可以使用

        访问其他组件中的数据
        this.props.history.location.state
        

        请注意,您必须使用 withRouter 包装您的组件才能访问历史对象

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-05-02
          • 2022-06-15
          • 1970-01-01
          • 1970-01-01
          • 2019-12-16
          • 2021-04-16
          相关资源
          最近更新 更多