React에서 부모 컴포넌트의 state를 자식 컴포넌트의 state로 이동시킬 수 있는 방법은 다음과 같다.


https://ourcodeworld.com/articles/read/409/how-to-update-parent-state-from-child-component-in-react



class Parent extends React.Component {
    constructor(props) {
        super(props)

        // Bind the this context to the handler function
        this.handler = this.handler.bind(this);

        // Set some state
        this.state = {
            messageShown: false
        };
    }

    // This method will be sent to the child component
    handler() {
        this.setState({
            messageShown: true
        });
    }

    // Render the child component and set the action property with the handler as value
    render() {
        return <Child action={this.handler} />
    }
}




class Child extends React.Component {
    render() {
        return (
            <div>
                {/* The button will execute the handler function set by the parent component */}
                <Button onClick={this.props.action} />
            </div>
        )
    }
}



일반 함수로 리턴할 수 있어서 좋다. 




https://www.quora.com/Why-doesnt-React-automatically-allow-child-components-to-call-setState-of-the-parent-component


  1. class ParentComponent extends React.Component {
  2. onClick() {
  3. const _childValue = this.state.childValue;
  4. this.setState({ childValue: _childValue + 1 });
  5. }
  6. render() {
  7. return (<ChildComponent value={this.state.childVvalue} onClick={this.onClick.bind(this)} />)
  8. }
  9. }
  10. class ChildComponent extends React.Component {
  11. render() {
  12. return (
  13. <span>
  14. <div>My value: {this.props.value} </div>
  15. <button onClick={this.props.onClick}>Increment</button>
  16. </span>
  17. )
  18. }
  19. }



Posted by '김용환'
,