【问题标题】:Passing states between components在组件之间传递状态
【发布时间】:2017-10-24 14:01:24
【问题描述】:

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

<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,

                })

            }

【问题讨论】:

  • 这两个组件如何相互连接?
  • 如果第二个组件放在第一个组件中,您可以将它(selectValue)作为道具传递给第二个组件。如果没有,您可以在您的应用程序中设置 redux,以便在整个应用程序中保持给定的状态。
  • 我将这两个组件渲染到另一个像这样的组件上。 我需要的状态是在 PostFooter。我想把它传递给 TextPost

标签: javascript reactjs components state


【解决方案1】:

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

检查这个工作的 sn-p:

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'/>

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 2020-10-15
    • 2021-09-13
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2017-09-06
    相关资源
    最近更新 更多