首页 > 解决方案 > 如何在没有父子关系的情况下将数据从一个组件发送到另一个组件

问题描述

家庭组件

    import React, { Component } from 'react';
    import Two from 'components/Two.jsx'
    import One from 'components/One.jsx'

    class Home extends Component {
      constructor(props){
        super(props)
        this.state = {

        }
         this.one = React.createRef();
      }

      getData = (data) => {
        this.one.current.finalClick(data);
      }

      render() {
        return (
            <div>
              <Two shareData={this.getData} />
              <One ref={this.one} />
            </div>
        );
      }
    }

    export default Home;

一个组件:

    import React from 'react'

    class One extends React.Component {
        constructor(props){
            super(props);
            this.state={

            }
        }

        finalClick = (data) => {
            console.log(data)
        }

        render(){
            return (
                <div>

                </div>
            )
        }
    }

    export default One;

两个组件:

    import React from 'react'

    class Two extends React.Component {
        handleClick = (data) => {
            this.props.shareData(data)
        }

        render(){
            return (
                <div>
                    <br/>
                    <button className="btn btn-info" onClick={() => this.handleClick('hellow')}>click</button>
                </div>
            )
        }
    }

    export default Two;

在这里,我试图从另一个组件中单击一个功能。这不是它的父组件或子组件。

首先,我单击两个按钮,它将数据发送到 Home 组件。它正在记录数据。

我想在 Home 组件中调用getData()后同时将数据发送到finalClick()方法。

我在One Component 中的finalClick()函数被点击,但数据没有通过。

标签: reactjs

解决方案


将要共享的数据保存为Home. 传递一个函数 from Hometo TwothroughTwo的 props 以更新数据。将数据从Home's 状态传递到Oneprops 中。


推荐阅读