2017-07-15 43 views
0

如何在句子結束時檢測輸入更改。 當我使用onChange時,狀態實時變化,但我想在句子結束或幾秒鐘後更改狀態。轉到下一個輸入時反應事件觸發

+2

也許你應該試着去'onFocusOut'? –

+0

使用'onBlur'而不是'onChange' –

+0

@RishabhMishra不,我想在焦點輸入時忽略事件「僅」。 – Sepehr

回答

1

這裏有兩種解決方案,解決方案之一是監聽輸入上的按鍵事件,並且只會在按下句點或回車鍵時更新狀態。如果您將注意力集中在輸入之外,解決方案二隻會更新狀態。點擊鏈接CodePen看到兩個解決方案的運行例子:https://codepen.io/w7sang/pen/zzbQzQ?editors=1111

// App 
 
class App extends React.Component{ 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     sentence: null 
 
    } 
 
    this.handleKeyUp = this.handleKeyUp.bind(this); 
 
    this.handleBlur = this.handleBlur.bind(this); 
 
    } 
 
    handleKeyUp(evt) { 
 
    if (evt.keyCode === 190 || evt.keyCode === 13) { 
 
     this.setState({ 
 
     sentence: evt.target.value 
 
     }); 
 
    } 
 
    } 
 
    handleBlur(evt) { 
 
    this.setState({ 
 
     sentence: evt.target.value 
 
    }) 
 
    } 
 
    render(){ 
 
    return(
 
     <div> 
 
     <h5>Sentence: (Start typing on any of the solution inputs)</h5> 
 
     {this.state.sentence} 
 
     <div> 
 
      <h5>Solution 1: On KeyUp (To update state, you must press period `.` or enter)</h5> 
 
      <input onKeyUp={this.handleKeyUp} /> 
 
     </div> 
 
     <div> 
 
      <h5>Solution 2: On Blur</h5> 
 
      <input onBlur={this.handleBlur} /> 
 
     </div> 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(<App />,document.getElementById('app'));

相關問題