简体   繁体   中英

React Set Child State From Parent Dropdown Menu

I have 2 js files. I want to change a state of Component2 from Component1.

class Component1 extends React.Component {
    constructor(props) {
        super(props);          
        this.state = {
            enable: false
        };
        this.enable = React.createRef();
        this.selector = this.selector.bind(this);

    selector() {
        this.setState({
            enable: true,
        })
    }

    render() {
        return ( 
            <div>
                <select><option>ENABLE</option></select>
                <OtherComponent>
                    <Component2 enable={this.state.enable} />  
                </OtherComponent>
            </div>
        )
    }

I want to set enable: true in Component2 via the <option> .

class Component2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            enable: false
        }
    }

    componentWillReceiverProps(nextProps) {
        this.setState({ enable: nextProps.enable, })
    }

    render()
        return <div>{this.state.enable}</div>

I haven't tried this before with a nested Component structure in the render().

We use props to pass the data from the parent's state to the children (there's no need to bind states of parent and child, or use Refs, or attempt to involve life-cycle methods):

 const { render } = ReactDOM class Component2 extends React.Component { render(){ return ( <div> Enabled: {this.props.isEnabled ? 'true' : 'false'} </div> ) } } class OtherComponent extends React.Component { render(){ return <div style={{backgroundColor:'black', color:'white', width:100}}>{this.props.children}</div> } } class Component1 extends React.Component { constructor(props) { super(props) this.selector = this.selector.bind(this) this.state = { enable: false } } selector() { this.setState({ enable: true }) } render() { return ( <div> <select onChange={this.selector}><option /><option>ENABLE</option></select> <OtherComponent> <Component2 isEnabled={this.state.enable} /> </OtherComponent> </div> ) } } render ( <Component1 />, document.getElementById('root') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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