2016-11-15 57 views
1

輸入密鑰按下後,我想清除textarea內容。但是,當輸入鍵按下文本區域清除,但輸入鍵仍然(新行)。我怎樣才能解決這個問題?輸入密鑰後清除文本區域

constructor(){ 
    this.state = { text : '' } 
} 

keypress(e){ 
    if(e.key == 'Enter'){ 
     this.setState({ 
     send_message: '' 
     }) 
    } 
} 

<textarea value={this.state.text} placeholder="Text" rows="1" className="form-textarea typing-area" onKeyPress={this.keypress.bind(this)}></textarea> 
+0

嘗試添加'返回false;'你的按鍵功能 –

回答

3

您可以使用event.preventDefault時,關鍵是 '回車':

class App extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { text : '' } 
 
    this.handleChange = this.handleChange.bind(this); 
 
    this.keypress = this.keypress.bind(this); 
 
    } 
 
    
 
    handleChange(event) { 
 
    this.setState({text: event.target.value}); 
 
    } 
 
    
 
    keypress(e){ 
 
    if(e.key === 'Enter'){ 
 
     e.preventDefault(); 
 
     this.setState({ 
 
     send_message: this.state.text, 
 
     text: '', 
 
     }); 
 
    } 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
     <textarea 
 
      value={this.state.text} 
 
      placeholder="Text" 
 
      rows="1" 
 
      className="form-textarea typing-area" 
 
      onChange={this.handleChange} 
 
      onKeyPress={this.keypress} 
 
     /> 
 
     <pre>{JSON.stringify(this.state, null, 2)}</pre> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+0

點上結束。謝謝 – rksh