在将内容存储到数据库后,我需要在react组件中清空输入字段。这就是我到目前为止所做的:
addPost (event) {
const content = event.target.value
methodInsert.call(
{ content },
(error) => {
if (!error) {
event.target.value = ''
}
}
)
}
渲染()
<Input
onBlur={this.addPost.bind(this)}
/>
我收到错误
Warning: This synthetic event is reused for performance reasons.
If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null.
If you must keep the original synthetic event around, use event.persist().
答案 0 :(得分:0)
您的输入需要一个onChange
处理程序,以便在发生任何更改时更新组件的状态。您还需要一个onSubmit
处理程序来处理您的提交逻辑,然后使用this.setState
清除输入,将其值设置为空。
我建议您阅读React文档中的Controlled Components。
以下是如何实现这一目标的示例:
class Example extends React.PureComponent {
constructor( props ) {
super( props );
this.state = {
inputValue = ""
}
this.handleChange = this.handleChange.bind( this );
this.handleSubmit = this.handleSubmit.bind( this );
}
handleChange( e ) {
this.setState({
inputValue: e.target.value
});
}
handleSubmit( e ) {
e.preventDefault();
// .. do your stuff and then
this.setState({
inputValue: ""
});
}
render() {
<form onSubmit={ this.handleSubmit }>
<input type="text"
placeholder="Controlled input"
onChange={ this.handleChange }
value={ this.state.inputValue } />
<button>Submit</button>
</form>
}
}