简体   繁体   中英

How to use setState and eventHandler both at a time for arrays in reactjs?

I'm new to React and I'm unable to use setState with eventHandlerMethod ( event.target.value ). My array is not getting modified. The same previous value is being printed everytime without changing anything.

This is my code

 class App extends Component {
  state={
    userName : ["prakash" , "Shree Harsha"]
  }

  clickChangeListener = (event) =>{
   // console.log(this.state.userName[0])
    this.setState=({ userName : [event.target.value , event.target.value]});
  }
   render(){
    return (
      <div className="App">
        <h1>Welcome to react app</h1>
        <UserInput click={this.clickChangeListener}/>
       <UserOutput  
                   name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
       <UserOutput name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
       <UserOutput name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
      </div>
    );
  }
}

What changes should I make so that my code works?

Just remove the = char.

Like the following:

this.setState({ userName : [event.target.value , event.target.value]});

setState is a function, read further here: https://reactjs.org/docs/react-component.html#setstate

I hope that helps!

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