javascript - 在组件之间传递状态

标签 javascript reactjs components state

我正在尝试根据另一个组件的状态执行一些操作。我有一个选择框,当用户更改选项时我会更改状态。

<div className="post_privacy_div float_left">

    <select className="review_privacy_select" onChange={this.commentOption}>

        <option value="Comments with filter">Comments with filter</option>

        <option value="Enable comments">Enable all comments</option>

        <option value="Disable comments">Disable all comments</option>

    </select>
</div>

函数

commentOption(e) {

        this.setState({selectValue: e.target.value});
}

因此状态更改已成功完成。现在我想将此状态传递给另一个组件。我该怎么做?

基本上我正在尝试这样做,但在另一个组件中

   if (this.state.selectValue === 'Enable comments') {

                this.setState({

                    pendingcomment: !this.state.pendingcomment,

                })

            } else if (this.state.selectValue === 'Disable comments') {

                this.setState({

                    pendingcomment: false,
                    allcomment: false,

                })

            } else {

                this.setState({

                    pendingcomment: true,
                    allcomment: true,

                })

            }

最佳答案

在这种情况下,维护 parent 组件中的值,并将该值和函数从父组件传递到 Child1 (需要传递函数来更改父组件中的值),将值传递给 Child2

检查这个工作片段:

class Parent extends React.Component {
    constructor(){
       super();
       this.state = { value: null}
       this.change = this.change.bind(this)
    }
    
    change(value){
       this.setState({value})
    }
    
    render(){
       return(
          <div>
             <Child1 value={this.state.value} change={this.change}/>
             <Child2 value={this.state.value}/>
          </div>
       )
    }      
}

class Child1 extends React.Component {
   render(){
      return(
         <div>
           In Child1:
           <select value={this.props.value} onChange={(e) => this.props.change(e.target.value)}>
              <option value='1'>1</option>
              <option value='2'>2</option>
              <option value='3'>3</option>
           </select>
         </div>
      )
   }
}

class Child2 extends React.Component {
   render(){
      return(
         <div>In Child2: {this.props.value} </div>
      )
   }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

关于javascript - 在组件之间传递状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154760/

相关文章:

javascript - 将外部 HTML 添加到 React 组件不起作用

javascript - 将内插零插入javascript中的日期数组

javascript - Phonegap 和 Google Analytics 无法正常工作

javascript - 保留 Azure 移动服务的自定义 API 调用的用户身份验证

node.js - 在 React 中上传文件并将其发送到 Express 服务器

java - 优化Java中具有大量组件的JFrame的绘制

javascript - Cypress 单选按钮断言

javascript - React onClick 事件触发点击子元素

javascript - 如何在 react 中验证输入字段

javascript - 如何防止外部 CSS 添加和覆盖 ReactJS 组件样式