我是 ReactJS 的新手,正在尝试获取搜索输入框的值并将其存储在状态中。
我的代码:
<form className="search-form" onSubmit={this.handleSubmit}>
<input type="search" name="search" ref={(input) => this.query = input}
placeholder="Search..." />
<button className="search-button" type="submit" id="submit">Go!</button>
</form>
内部构造函数:
this.handleSubmit = this.handleSubmit.bind(this);
和
handleSubmit = e => {
e.preventDefault();
this.setState({search: this.query.value});
console.log(this.state.search) //Returns undefined
e.currentTarget.reset();
}
非常感谢任何帮助。
最佳答案
我建议您使用受控输入方法。
state = {
value: null,
}
handleValue = (e) => this.setState({ value: e.target.value });
那么你不必使用ref
。
<input
type="search"
name="search"
onChange={this.handleValue}
placeholder="Search..."
/>
关于javascript - 在 ReactJS 中获取状态中的搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810381/