简体   繁体   中英

why is my bind not working in constructor

I'm doing a very simple two button state. where if i click abutton, A component displays and if bbutton is clicked then component B. I'm mapping through array of items so that each of them have their own buttons state. Lets say if I click item 1's button B then I want only first Item B to show. Right now All of them gets triggered at once. I have bounded each of them in the constructor but still i'm unable to get only the once the once clicked to trigger and show the relevant component.

class Home extends Component {


  constructor(props) {
    super(props);
    this.state = {
      lists: []
      showA: true,
      showB: false
    }
    this.aButtonHandler = this.aButtonHandler.bind(this);
    this.bButtonHandler = this.bButtonHandler.bind(this);
  }



  aButtonHandler = (e) => {
    this.setState({
      showA: true,
      showB: false 
    })
  }



  bButtonHandler = (e) => {
    this.setState({
      showA: false,
      showB: true
    })
  }




 render(){
    return (
      <div> 

       {this.state.lists.map(detail => 
        <li>{detail.id}</li>
        <button onClick={(e) => this.aButtonHandler(e)} >see A</button>
        <button onClick={(e) => this.bButtonHandler(e)} >see B</button> 

        {this.state.showA ? 
          <ComponentA />  : null
        }

        {this.state.showB ? 
           <ComponentB />  : null
         }
       )}

       </div>
      )
    }  

If you are using arrow functions no need to bind functions.

If you want to bind then change it to normal function like this.

aButtonHandler(e){...}
bButtonHandler(e){...}

If you want to use bind in constructor no need to use arrow function, just use regular functions and pass the function directly to onClick

aButtonHandler(e) { this.setState({ showA: true, showB: false }); }

bButtonHandler(e) { this.setState({ showA: false, showB: true }); }

render() {
  return (
    <div>
      {this.state.lists.map(detail => (
        <div>
          <li>{detail.id}</li>
          <button onClick={this.aButtonHandler}>see A</button>
          <button onClick={this.bButtonHandler}>see B</button>
          {this.state.showA ? <ComponentA /> : null}
          {this.state.showA ? <ComponentB /> : null}
        </div>
      ))}
    </div>
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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