javascript - setState() 不采取进一步的论点 (e) 来改变价值
问题描述
我想用输入框的当前值附加状态的先前值, 但是当我使用setState函数时,它以某种方式不允许将事件作为参数传递。
问题:setState(prev,props, e ) setState函数未检测到第三个参数 (e)。
e.target.value 即将到来未定义
这是我的代码:
import React , {Component} from 'react'
class Todo extends Component{
constructor(){
super()
this.state={toDo:[],currentInput:"name"}
// bind the events
this.addItem=this.addItem.bind(this)
this.changeList=this.changeList.bind(this)
}
addItem(e){
// prevent default
e.preventDefault();
// this part is left
}
changeList(e){
this.setState(function (prev,props,e){
console.log(prev.currentInput)
return {currentInput:prev.currentInput+e.target.value} // this part is causing problem
})
}
render(){
return(
<div className="App">
<h1>Add your tasks</h1>
<form onSubmit={this.addItem}>
<input type="text" value={this.state.currentInput} onChange={this.changeList} ></input>
<input type="submit"></input>
</form>
<div className="List">
<h3>Remaining items:-</h3>
<ul>
</ul>
</div>
</div>
)
}
}
export default Todo
解决方案
您实际上不需要这样做prev.currentInput+e.target.value
,因为 e.target.value 将是当前输入值...如果您alpha
输入 input 它实际上会评估为,namenamealpha
而我的猜测是您期望namealpha
但如果你仍然想让它在这里工作,你应该怎么做
import React , {Component} from 'react'
class Todo extends Component{
constructor(){
super()
this.state={toDo:[],currentInput:"name"}
}
addItem = (e) => {
e.preventDefault();
}
changeList = (e) => {
const newValue = e.target.value;
this.setState((state) => {
console.log({state, newValue})
return({
currentInput: state.currentInput + newValue
})
});
}
render(){
return(
<div className="App">
<h1>Add your tasks</h1>
<form onSubmit={this.addItem}>
<input type="text" value={this.state.currentInput} onChange={this.changeList} ></input>
<input type="submit"></input>
</form>
<div className="List">
<h3>Remaining items:-</h3>
<ul>
</ul>
</div>
</div>
)
}
}
export default Todo
或者,理想情况下,您也可以使用这样的钩子
import React , { useState }from 'react'
const Todo = () => {
const [currentInput, setCurrentInput] = useState('name');
return(
<div className="App">
<h1>Add your tasks</h1>
<form onSubmit={() => console.log('submit')}>
<input type="text" value={currentInput} onChange={(e) => setCurrentInput(e.target.value)} ></input>
<input type="submit"></input>
</form>
<div className="List">
<h3>Remaining items:-</h3>
<ul>
</ul>
</div>
</div>
)
}
export default Todo
推荐阅读
- javascript - 替换数组特定键值中的子字符串
- visual-studio - 错误 opencv_world310d.dll OPENCV - VISUALSTUDIO
- gnuplot - 生成垂直比例曲线gnuplot
- c# - 使用 MVVM Light 时处理复选框的最佳方法是什么
- python - QtWidgets.QProgressBar.setTextVisible(False) 导致滞后
- r - 使用带有不同 funs() 参数的 summarise_at() 以及其他与误差幅度相关的 Q
- php - 从数据库中检索数据时未定义的错误 Laravel
- javascript - mediasource webm 无法正常播放
- python - 如何用python测量图像中的距离?
- sql - SQLplus 行限制