在React JS中按下Enter键时如何获取输入文本字段值?
问题描述:
我想在用户按下键盘上的Enter键时传递textfield
值.在onChange()
事件中,我正在获取textbox
的值,但是如何在按下enter
键时获取该值?
I want to pass textfield
values when user press enter key from keyboard. In onChange()
event, I am getting the value of the textbox
, but How to get this value when enter
key is pressed ?
代码:
import TextField from 'material-ui/TextField';
class CartridgeShell extends Component {
constructor(props) {
super(props);
this.state = {value:''}
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({ value: e.target.value });
}
render(){
return(
<TextField
hintText="First Name"
floatingLabelText="First Name*"
value={this.state.value}
onChange={this.handleChange}
fullWidth={true} />
)
}
}
答
使用onKeyDown
事件,并在其中检查用户按下的键的键控代码. Enter
键的键代码为13,检查代码并在其中放置逻辑.
Use onKeyDown
event, and inside that check the key code of the key pressed by user. Key code of Enter
key is 13, check the code and put the logic there.
检查此示例:
class CartridgeShell extends React.Component {
constructor(props) {
super(props);
this.state = {value:''}
this.handleChange = this.handleChange.bind(this);
this.keyPress = this.keyPress.bind(this);
}
handleChange(e) {
this.setState({ value: e.target.value });
}
keyPress(e){
if(e.keyCode == 13){
console.log('value', e.target.value);
// put the login here
}
}
render(){
return(
<input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />
)
}
}
ReactDOM.render(<CartridgeShell/>, 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' />
注意:用Material-Ui TextField
替换input
元素,并定义其他属性.
Note: Replace the input
element by Material-Ui TextField
and define the other properties also.