简体   繁体   English

从父下拉菜单中反应设置子状态

[英]React Set Child State From Parent Dropdown Menu

I have 2 js files.我有 2 个 js 文件。 I want to change a state of Component2 from Component1.我想从 Component1 更改 Component2 的状态。

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> .我想通过<option>在 Component2 中设置enable: true

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().我之前没有在 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):我们使用 props 将父状态的数据传递给子级(不需要绑定父子状态,或者使用 Refs,或者尝试涉及生命周期方法):

 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>

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

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