2017-07-29 36 views
0

我需要在內容存儲到數據庫之後清空反應組件中的輸入字段。這是我做過什麼至今:ReactJS:處理其值後的空輸入字段

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(). 
+1

太好了!問題是什麼? – PeterMader

+1

使輸入受控,然後將setState設置爲空字符串。 – SamHH

+0

@PeterMader查看更新的文章 – user3142695

回答

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> 
    } 
} 
+0

但提交後,輸入字段的值仍然存在。它應該是空的。 – user3142695

+0

@ user3142695我的錯誤...我忘了在''上包含'value = {this.state.inputValue}'。繼續,並檢查它現在的工作更新:) –