如何通过调用其父组件中的函数来更改子组件中的状态?

时间:2016-12-26 20:21:14

标签: javascript reactjs

每次调用其父组件中的函数时,我都会尝试更改子组件中的状态。我该怎么做呢?例如,

class ParentComponent extends Component {
function onClick(){
  // some function here to change child components state
}
render(){
  return (
         <div>
         <ChildComponent />
         <button onClick={this.onClick.bind(this)}>
         </div>
        )
  }

class ChildComponent extends Component {
constructor(props){
  super(props)
  this.state = {
     MyState: 1
  }
}
render(){
  return(
    <div>
      {this.state.MyState}
    </div>
  )
}
}

3 个答案:

答案 0 :(得分:1)

根据我的理解,你正在努力实现这个目标:

class ParentComponent extends Component {
constructor(props){
  super(props)
  this.state = {
     MyState: 1
  }
}

function onClick(){
  this.setState({MyState:this.state.MyState + 1})
}
render(){
  return (
         <div>
         <ChildComponent sendToChild={this.state.MyState}/>
         <button onClick={this.onClick.bind(this)}>
         </div>
        )
  }

class ChildComponent extends Component {

render(){
  return(
    <div>
      {this.props.MyState}
    </div>
  )
}
}

答案 1 :(得分:0)

onClick处理程序中调用setState - 这会导致在ParentComponent和任何子组件中重新呈现(除非组件在shouldComponentUpdate中返回false,但是您没有实现此功能)。但是,即使在当前重新渲染时,您的子组件也不会在视觉上发生变化,因为它没有道具。

不确定您想要实现什么,但是如果要将状态MyState从ChildComponent移动到ParentComponent并将MyState作为道具传递给ChildComponent,并且onClick处理程序调用{​​{1}}并增加setState,然后ChildComponent将在视觉上更新。

答案 2 :(得分:0)

onClick处理程序放在子组件lift the state up中,或通过道具传递onClick

你想要完成什么?