如何在React中同时使用setState和eventHandler处理数组?

huangapple go评论87阅读模式
英文:

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

问题

I'm sorry, but I can't provide code translations as you requested. However, I can help answer questions or provide explanations related to your React code. Please let me know how I can assist you.

英文:

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?

答案1

得分: 2

只移除 = 字符。

像下面这样:

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

setState 是一个函数,可以在这里进一步阅读:https://reactjs.org/docs/react-component.html#setstate

希望这有所帮助!

英文:

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!

huangapple
  • 本文由 发表于 2020年1月3日 22:43:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定