我可以将 1 项添加到它记录的数组中["50"]在控制台中。但是当我尝试添加第二个值时,我收到此错误“currentScores.push 不是函数”。这样的做法是错误的吗?
class Scores extends Component {
constructor() {
super();
this.addScore = this.addScore.bind(this);
this.handleScoreChange = this.handleScoreChange.bind(this);
this.state = {
scores: [],
scoreInput: '',
};
}
addScore() {
const currentScores = this.state.scores;
const newScores = currentScores.push(this.state.scoreInput);
this.setState({ scores: newScores });
console.log(this.state.scores);
}
handleScoreChange(e) {
this.setState({ scoreInput: e.target.value });
}
render() {
const scores = this.state.scores;
return (
<input name="score" type="text" placeholder="Score" onChange={this.handleScoreChange}/>
<button onClick={this.addScore(this.state.scoreInput)}>add</button>
);
}
}
export default Scores;
当你使用时有两件事push
它不返回new array
。利用concat
并将该值绑定到 addUser 函数。
还将您的元素包装在单个 div 中并编写您的console.log()
语句输出状态值callback
setState 的函数,因为它需要一些时间来改变
class Scores extends React.Component {
constructor() {
super();
this.addScore = this.addScore.bind(this);
this.handleScoreChange = this.handleScoreChange.bind(this);
this.state = {
scores: [],
scoreInput: '',
};
}
addScore() {
const currentScores = this.state.scores;
const newScores = currentScores.concat(this.state.scoreInput);
this.setState({ scores: newScores }, function(){
console.log(this.state.scores);
});
}
handleScoreChange(e) {
this.setState({ scoreInput: e.target.value });
}
render() {
const scores = this.state.scores;
return (
<div>
<input name="score" type="text" placeholder="Score" onChange={this.handleScoreChange}/>
<button onClick={this.addScore.bind(this, this.state.scoreInput)}>add</button></div>
);
}
}
ReactDOM.render(<Scores/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)