简体   繁体   English

如何解决来自父母的孩子的功能反应?

[英]How to fire a function in child from parent in react?

My React app has three components. 我的React应用程序有三个组件。 Two of them are child components and the other is parent. 其中两个是子组件,另一个是父组件。 I need to pass a data (projectId) from one child component to the other child through the parent component and after receiving the data, fire a function. 我需要通过父组件将数据(projectId)从一个子组件传递给另一个子组件,并在接收到数据后触发一个函数。 As my example, I'm sending projectId from ChildOne to Parent and then send projectId from Parent to ChildTwo. 作为我的例子,我将projectId从ChildOne发送到Parent,然后将projectId从Parent发送到ChildTwo。 ChildTwo has a function called setProject(projectId) and I need to fire it once the projectID is received. ChildTwo有一个名为setProject(projectId)的函数,我需要在收到projectID后触发它。 The problem is I can't get the function getProjectId fired in ChildTwo by clicking on the button in ChildOne. 问题是我无法通过单击ChildOne中的按钮来获取在ChildTwo中触发的函数getProjectId。 I also tried with componentDidMount and componentWillReceiveProps which are not working for me. 我也尝试过componentDidMount和componentWillReceiveProps,它们对我不起作用。 How can I do this? 我怎样才能做到这一点?

Here what I tried 这是我尝试过的

ChildOne : ChildOne:

class ChildOne extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          projectId: 3,
        };
    }

    sendProjectId = (projectId) => {
       this.props.sendId(projectId)
    }

    render() {
       return(
         <button onClick={() => this.sendProjectId(this.state.projectId)}>
            Click
         </button>
       )
    }
}

Parent: 家长:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          projectId: '',
        };
    }

    getId = (proId) => {
       this.setState({
          projectId : proId
       })
    }

    render() {
       return(
         <div>
           <CildOne sendId={this.getId} />

           <CildTwo sendOneId={this.state.projectId} />
         </div>
       )
    }
}

ChildTwo: ChildTwo:

class ChildTwo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          projectId: '',
        };
    }

    getProjectId = (this.props.sendOneId) => {
       //Do something with this.props.sendOneId
    }

    render() {
       return(
         <div></div>
       )
    }
}

This would depend on what ChildTwo wants to accomplish with the said data. 这取决于ChildTwo希望用所述数据完成什么。

Case 1: 情况1:

ChildTwo intends to fetch some data with the corresponding projectId and display it in the component. ChildTwo打算使用相应的projectId获取一些数据并将其显示在组件中。 Then, you can easily fetch this data in the parent component and pass the data down as props . 然后,您可以轻松地在父组件中获取此数据,并将数据作为props传递下来。

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          projectId: '',
          dataForChildTwo: null,
        };
    }

    getId = (proId) => {
       this.setState({
          projectId : proId,
          dataForChildTwo: fetchData(proId)
       })
    }

    render() {
       return(
         <div>
           <CildOne sendId={this.getId} />

           <CildTwo data={this.state.dataForChildTwo} />
         </div>
       )
    }
}

Case 2: 案例2:

ChildTwo intends to make some change to something inside it when projectId changes. ChildTwo打算在projectId更改时对其中的某些内容进行一些更改。 Then you can use componentDidUpdate hook to see if prop changed and respond to it. 然后,您可以使用componentDidUpdate挂钩来查看prop是否已更改并对其进行响应。

class ChildTwo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          projectId: '',
        };
    }

    getProjectId = (this.props.sendOneId) => {
       //Do something with this.props.sendOneId
    }

    componentDidUpdate(prevProps) {
      if(this.props.projectId!==prevProps.projectId) {
        // do something
      }
    }

    render() {
       return(
         <div></div>
       )
    }
}

Case 3 : 案例3

If none of the above cases work for you, then you can manually reload the complete component when the projectId changes using a key attribute: 如果上述任何一种情况都不适合您,则可以在projectId使用key属性更改时手动重新加载完整组件:

<CildTwo key={this.state.projectId} sendOneId={this.state.projectId} />

Note: This reloads the whole component quite unnecessarily. 注意:这会非常不必要地重新加载整个组件。

Our you can try a functional component or hooks if you want to set some state 如果你想设置一些状态,我们你可以尝试一个功能组件或钩子

function ChildOne(props) {
  const [projectId, setProjectId] = useState(3);
  function sendProjectId(data){
       props.sendId(projectId)
    }
   return(
         <button onClick={() => sendProjectId(projectId)}>
            Click
         </button>
       )
}



function ChildTwo(props) {
  const [state, setState] = useState('')
  function getProjectId(data) {
       //Do something with this.props.sendOneId
       console.log(`data here ${data}`)
       return false;
    }
    getProjectId(props.sendOneId)
  return (
    <div>
    </div>
  )
}


function Parent(){
   const [projectId, setProjectId] = useState('');
   function getId(proId) {
     setProjectId(proId)
   }
   return(
         <div>
           <ChildOne sendId={getId} />

           <ChildTwo sendOneId={projectId} />
         </div>
       )
}



You did a mistake in getProjectId function of ChildTwo component. 你在ChildTwo组件的getProjectId函数中犯了一个错误。

Your function cannot receive anything as a parameter from prop. 您的函数无法从prop接收任何参数。

So, your function should look like: 所以,你的功能应该是这样的:

getProjectId = (sendOneId) => {
   //Do something with this.props.sendOneId
}

Then you should use componentWillReceiveProps like this: 然后你应该像这样使用componentWillReceiveProps

componentWillReceiveProps(nextProps) {
  if (this.props.sendOneId !== nextProps.sendOneId) {
    this.getProjectId(nextProps.sendOneId);
  }
}

Here is a working codesandbox example that I created to fix your problem: https://codesandbox.io/s/5v4rn7qnll 这是我为解决您的问题而创建的工作代码框示例: https ://codesandbox.io/s/5v4rn7qnll

You should probably use componentDidUpdate with a condition to check to see whether the projectId in state needs to be updated when sendOneId changes. 您应该使用componentDidUpdate和条件来检查在sendOneId更改时是否需要更新处于sendOneId state You can then use setState s callback to call getProjectId : 然后,您可以使用setState的回调来调用getProjectId

componentDidUpdate() {
  const { projectId: currentProjectId } = this.state;
  const { sendOneId: projectId } = this.props;
  if (projectId !== currentProjectId) {
    this.setState({ projectId }, () => this.getProjectId());
  }
}

Full working example: 完整的工作示例:

 class ChildOne extends React.Component { constructor(props) { super(props); this.state = { projectId: 3, }; } sendProjectId = (projectId) => { this.props.sendId(projectId) } render() { return ( <button onClick={() => this.sendProjectId(this.state.projectId)}> Click </button> ); } } class Parent extends React.Component { constructor(props) { super(props); this.state = { projectId: '', }; } getId = (projectId) => { this.setState({ projectId }); } render() { return ( <div> <ChildOne sendId={this.getId} /> <ChildTwo sendOneId={this.state.projectId} /> </div> ) } } class ChildTwo extends React.Component { constructor(props) { super(props); this.state = { projectId: '', }; } componentDidUpdate() { const { projectId: currentProjectId } = this.state; const { sendOneId: projectId } = this.props; if (projectId !== currentProjectId) { this.setState({ projectId }, () => this.getProjectId()); } } getProjectId = () => { console.log(this.state.projectId); } render() { return ( <div></div> ); } } ReactDOM.render( <Parent />, document.getElementById('container') ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="container"></div> 

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

相关问题 如何使用按钮单击中的数据从子组件到父组件触发 setState 函数 - How to fire a setState function in react from child componenet to parent componenet with data from a button click 反应是否有可能从另一个孩子身上触发一个孩子的功能? - react is it possible to fire function implemnted on one child from another child? 如何在父动画开始时触发jquery子函数 - how to fire a jquery child function at the start of parent animation 如何从子道具React 15.5.0调用父函数 - How to call parent function from child prop React 15.5.0 React.js - 如何使用来自孩子的参数在父级中执行函数 - React.js - How to execute function in parent with arguments from child 如何从父组件调用 React/Typescript 子组件 function? - How to call React/Typescript child component function from parent component? 如何在本机反应中将函数从孩子传递给父母? - How to pass a function from child to parent in react native? 如何在反应中将自定义 onClick function 从父母传递给孩子 - How to pass a custom onClick function from parent to child in react 如何从 React 中的父组件调用子 function - How can I call Child function from Parent Component in React 如何从孩子呼叫父母 function - react-native - How to call a parent function from a child - react-native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM