Javascript 如何为物料UI文本字段正确设置onKeyPress事件?
我从Material UI中得到了如下TextField组件:Javascript 如何为物料UI文本字段正确设置onKeyPress事件?,javascript,reactjs,material-ui,Javascript,Reactjs,Material Ui,我从Material UI中得到了如下TextField组件: <TextField id="todo-textarea" label="Enter new todo" placeholder="ToDo" onChange={this.props.toDoOnChange} onKeyPress={(ev) => { if (ev.ctrlKey &&
<TextField
id="todo-textarea"
label="Enter new todo"
placeholder="ToDo"
onChange={this.props.toDoOnChange}
onKeyPress={(ev) => {
if (ev.ctrlKey && ev.key === 'Enter') {
this.props.addHandler
}
}}
value={this.props.toDoValue}
className={classes.textField}
margin="normal"
helperText="Press Ctrl+Enter to add new ToDo"
/>
我想调用addHandler方法,当我按ctrl+enter时,它会在待办事项字段中添加输入值,但这个方法不起作用。目前,我通过按下按钮调用addHandler方法,效果很好。从onKeyPress调用方法看起来像是smth错了,因为我在控制台中看到了这样一条消息:应该是赋值或函数调用,而看到的是一个表达式没有未使用的表达式
你能告诉我这里怎么了吗
您应该像这样调用函数
现在代码看起来像
谢谢,现在可以用了。正如您所看到的,在onChange事件中,不需要在括号中调用函数,所以我不希望在这里需要它。。。
this.props.addHandler() // with the brackets
<TextField
id="todo-textarea"
label="Enter new todo"
placeholder="ToDo"
onChange={this.props.toDoOnChange}
onKeyPress={(ev) => {
if (ev.ctrlKey && ev.key === 'Enter') {
this.props.addHandler() // here was the mistake
}
}}
value={this.props.toDoValue}
className={classes.textField}
margin="normal"
helperText="Press Ctrl+Enter to add new ToDo"
/>