Reactjs根据子组件的类更改组件的状态

时间:2018-01-30 06:49:25

标签: reactjs

我现在已经使用reactjs很长一段时间了,到目前为止一直很好。然而有一件事我有点被困住了。我试图在点击时更改父组件的状态,但仅当子组件具有某个类时,否则不会。

让我在这里为您提供代码示例:

父组件:

class Parent extends React.Component{
 constructor(){
    super();
    this.state = {
      pageState: false
    }
  }

  changeState(){
    this.setState({pageState: !this.state.pageState});
  }

  render(){
    return(

      <div id="app">
        <ul>
          <Child sendState={this.changeState.bind(this)} heading="Home"/>
          <Child sendState={this.changeState.bind(this)} heading="About"/>
          <Child sendState={this.changeState.bind(this)} heading="Contact"/>
          <Child sendState={this.changeState.bind(this)} heading="Work"/>
        </ul>
      </div>

    )
  }

}

render(<Parent/>, document.getElementById("app-wrapper"));

子组件

class Child extends React.Component{

 render(){
  return(
    <li className="list_element">
     <div className="card_block" onClick={this.props.sendState.bind(this)}>
      <h2>{this.props.heading}</h2>
     </div>
    <li>
  )
 }
}

所以基本上我想要实现的是,当点击“li”中的卡片时,状态需要改变,但前提是父母“li”具有“当前”类。所以点击卡元素,检查它的类,如果它有“当前”类,则更改状态。

无论如何这可以成为可能吗?

1 个答案:

答案 0 :(得分:1)

您需要从className组件内的点击事件处理程序将<Parent />作为道具发送到<Child />组件。通过在注释中进行必要的更改来尝试以下代码。 工作小提琴:https://jsfiddle.net/kartalerkoc/rfra9uep/3/

更新:根据您对JQuery的评论,我更新了<Child />组件的onClickCard()render()方法,以便将refs用于您的问题。另外,更新了小提琴。

class Parent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      pageState: false
    }
    // bind this to your changeState function
    this.changeState = this.changeState.bind(this);
  }

  // Revise your changeState function
  changeState(textClassName){
    if (textClassName.includes("current")) {
      console.log("true - current is in class name");
        this.setState({pageState: !this.state.pageState});
    }
  }

  // edit the prop function for <Child />
  render(){
    return(
      <div id="app">
        <ul>
          <Child heading={"Home"} changeState={this.changeState} />
          <Child heading={"About"} changeState={this.changeState} />
          <Child heading={"Contact"} changeState={this.changeState} />
          <Child heading={"Work"} changeState={this.changeState} />
        </ul>
      </div>

    )
  }

}

class Child extends React.Component{
 // add onClick event handler for card
 onClickCard() {
    let refValue = "li"+this.props.heading;
    let textClassName = this.refs[refValue].className;
    this.props.changeState(textClassName);
 };

 // Edit your onClick event handler on div element
 render(){
 let refValue = "li"+this.props.heading;
 console.log(refValue);
  return(
    <li className={"list_element current"} id={refValue} ref={refValue}>
     <div className="card_block" onClick={this.onClickCard.bind(this)}>
      <h2>{this.props.heading}</h2>
     </div>
   </li>
  )
 }
};

ReactDOM.render(<Parent />, document.getElementById('app-wrapper'));