【发布时间】:2019-11-14 15:13:41
【问题描述】:
当前正在尝试使用 setState 清除受控输入,
向输入字段添加一个值并使用 setState 清除它
清除状态的函数
createNewBoard = (e) => {
e.preventDefault();
const newItem = { boardname: this.state.currentValue, todo: []};
const updatedList = [...this.state.boards, newItem]
this.setState({
boards: updatedList,
currentValue: ''
});
}
将 props 传递给组件
render() {
return(
<>
{ this.state.isBoardOpen ?
<ActiveCreateBoard
toggleCreateBoard={this.toggleCreateBoard}
onChange={this.onChange}
currentValue={this.currentValue}
createNewBoard={this.createNewBoard}
/> : <CreateBoard toggleCreateBoard={this.toggleCreateBoard}/> }
<ShowAllBoards boards={this.state.boards}/>
</>
)
}
不更新输入字段的组件本身
const ActiveCreateBoard = ({ toggleCreateBoard, onChange, currentValue, createNewBoard }) => {
return(
<div className="card">
<div className="card-body">
<form onSubmit={createNewBoard}>
<h4>Pick a board name</h4>
<input
type="text"
onChange={onChange}
value={currentValue}/>
</form>
</div>
<button onClick={toggleCreateBoard}>close</button>
</div>
)
}
this.setState 正在清除 state 中的 currentValue,但输入字段的值并未反映 state 中的更新
【问题讨论】:
-
请添加来自
render()设置currentValue的行。 -
如果您成功地从
this和this.state中解构createNewBoard和onChange,您的代码应该可以正常工作。如果可能,请在此处分享您的整个组件(作为工作副本)。 -
更新了更多信息,谢谢!
标签: javascript reactjs