无法清除具有setstate的受控输入

时间:2019-07-03 22:00:23

标签: javascript reactjs

当前尝试使用setState清除受控输入,

在输入字段中添加一个值,并使用setState清除它

  

清除状态的功能

createNewBoard = (e) => {
  e.preventDefault();
  const newItem = { boardname: this.state.currentValue, todo: []};
  const updatedList = [...this.state.boards, newItem]
  this.setState({ 
    boards: updatedList, 
    currentValue: '' 
 });
}
  

将道具传递到组件

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清除状态中的currentValue,但输入字段的值不反映状态中的更新

1 个答案:

答案 0 :(得分:0)

您的输入字段未更新,因为您传递了this.currentValue,该字段将是未定义的:

<ActiveCreateBoard 
  toggleCreateBoard={this.toggleCreateBoard} 
  onChange={this.onChange} 
  currentValue={this.currentValue}
  createNewBoard={this.createNewBoard} 
/>

相反,您需要从state传递值。

更改为使用this.state.currentValue

<ActiveCreateBoard 
  toggleCreateBoard={this.toggleCreateBoard} 
  onChange={this.onChange} 
  currentValue={this.state.currentValue} // <---
  createNewBoard={this.createNewBoard} 
/>