简体   繁体   English

从子组件更新父组件状态

[英]Update Parent Component State from Child Component

I am setting a state into child component on event perform and want to sent this to Parent component. 我在事件执行时将状态设置为子组件,并希望将此状态发送给父组件。 I searched for this on SO. 我在SO上搜索了此内容。 But still didn't found any way to do this. 但是仍然没有找到任何方法可以做到这一点。

Let say i have a parent component Home , and have child component User . 假设我有一个组件Home ,有一个组件User I am performing some event in User component, and at that time, i want to pass data to Home component. 我正在User组件中执行一些事件,当时,我想将数据传递给Home组件。 How can i do this? 我怎样才能做到这一点?

Below is my code: 下面是我的代码:

/* Parent component */

import React, { Component } from 'react';
import User from './user';

class Home extends React.Component{
    constructor(props){
        super(props)
        this.state = {
           isReportSent: false
        }   
    }
    render(){
        <Switch>
           <Route exact path="/" component={User}/>
        </Switch>
    }
}

/* child component */
class User extends React.Component{
    constructor(props){
        super(props)
    }
    render(){

    }
}

Note : My parent component is Routing component, in which i am routing my child component on particular path. 注意 :我的父组件是“路由”组件,在其中我要在特定路径上路由我的子组件。 So can't pass any function to child component. 因此不能将任何函数传递给子组件。

You can make use of render props in Routes to pass callback method to child which you can then use to update the parent 您可以在Routes中使用render道具将回调方法传递给子级,然后可以使用该方法来更新父级

import React, { Component } from 'react';
import User from './user';

class Home extends React.Component{
    constructor(props){
        super(props)
        this.state = {
           isReportSent: false
        }   
    }
    performUpdate = () => {

    }
    render(){
        <Switch>
           <Route exact path="/" render={(props) => <User {...props} performUpdate={this.performUpdate}/>}/>
        </Switch>
    }
}

/* child component */
class User extends React.Component{
    constructor(props){
        super(props)
    }

    handleClick=() => {
       this.props.performUpdate(); //call to inform parent about change
    }
    render(){

    }
}

You can actually pass a method, you just need to use the render prop 您实际上可以传递一个方法,只需要使用render属性

<Switch>
   <Route exact path="/" render={(props)=><User {...props} someMethod={someMethod} />}/>
</Switch>

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

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