ReactJS: setState on parent inside child component

后端 未结 7 1274
孤街浪徒
孤街浪徒 2020-12-02 10:18

What is the recommended pattern for doing a setState on a parent from a child component.

var Todos = React.createClass({
  getInitialState: function() {
             


        
相关标签:
7条回答
  • 2020-12-02 11:04

    I found the following working and simple solution to pass arguments from a child component to the parent component:

    //ChildExt component
    class ChildExt extends React.Component {
        render() {
            var handleForUpdate =   this.props.handleForUpdate;
            return (<div><button onClick={() => handleForUpdate('someNewVar')}>Push me</button></div>
            )
        }
    }
    
    //Parent component
    class ParentExt extends React.Component {   
        constructor(props) {
            super(props);
            var handleForUpdate = this.handleForUpdate.bind(this);
        }
        handleForUpdate(someArg){
                alert('We pass argument from Child to Parent: \n' + someArg);   
        }
    
        render() {
            var handleForUpdate =   this.handleForUpdate;    
            return (<div>
                        <ChildExt handleForUpdate = {handleForUpdate.bind(this)} /></div>)
        }
    }
    
    if(document.querySelector("#demo")){
        ReactDOM.render(
            <ParentExt />,
            document.querySelector("#demo")
        );
    }
    

    Look at JSFIDDLE

    0 讨论(0)
提交回复
热议问题