簡體   English   中英

狀態被清除,但是在React中提交表單后,輸入字段文本不存在

[英]state is cleared, but input field text is not after form is submitted in React

我正在一個簡單的待辦事項應用程序上進行練習,用戶可以在字段中鍵入待辦事項,然后單擊提交以將其添加到待辦事項列表中。

一旦使用'this.setState({newTodo:''}))'提交表單,我就設法清除了狀態(再次點擊Submit會添加一個空的待辦事項);

但是,輸入字段中的文本不會被清除。

const TodoItem = ({ text }) => <li>{text}</li>;

class App extends Component {
constructor(props) {
    super(props);

    this.state = {
        todos: ['walk dog', 'feed cat'],
        newTodo: ''
};

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e) {
    e.preventDefault();

    const todos = [...this.state.todos, this.state.newTodo];

    this.setState({ todos, newTodo: '' });
}

render() {
    const { newTodo } = this.state; 
    const todos = this.state.todos.map((todo, index) => <TodoItem key={index} text={todo} />);

    return (
        <div className="App">
            <form onSubmit={this.handleSubmit}>
                <h1>Simple Todo App</h1>

                <input
                    type="text"
                    name="newTodo"
                    value={this.newTodo}

                    onChange={e => this.setState({ [e.target.name]: e.target.value })}
                />

                <ol>
                  {todos}
                </ol>
                <button>SAVE</button>
            </form>
        </div>
    );
}
}

export default App;

感謝您的任何幫助。

this.newTodo是未定義的,請使用this.state.newTodo代替this.newTodo

<input
     type="text"
     name="newTodo"
     value={this.state.newTodo} 
      onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

要么:

const { newTodo } = this.state; 
<input
     type="text"
     name="newTodo"
     value={newTodo} 
      onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

之所以會看到添加了空newTodo的原因是因為newTodo的初始狀態為空,並且在handleSubmit中,無論它是否為空,您總是會傳遞它。 因此,在handleSubmit中檢查newTodo狀態,然后將newTodo添加到todos數組中。

 if(this.state.newTodo != “”){
      const todos = [...this.state.todos, this.state.newTodo];
 }

並將輸入字段值屬性值更改為newTodo

 <input value={newTodo} />

不要使用this.newTodo

在以下部分中:

<input
 type="text"
 name="newTodo"
 value={this.newTodo}
 onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

value={this.newTodo}更改為value={this.state.newTodo}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM