【问题标题】:How to properly set onKeyPress event for Material UI text field?如何为 Material UI 文本字段正确设置 onKeyPress 事件?
【发布时间】:2018-10-04 17:18:59
【问题描述】:

所以我有来自 Material UI 的 TextField 组件,如下所示:

<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"
        />

当我按下 ctrl+enter 时,我想调用 addHandler 方法(在 to-do 字段中添加输入值),但这东西不起作用。目前我通过按下按钮调用 addHandler 方法,效果很好。看起来好像从 onKeyPress 调用方法有问题,因为我在控制台中有这条消息:Expected an assignment or function call and instead saw an expression no-unused-expressions

你能告诉我这里有什么问题吗?

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    你应该这样调用函数

       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"
        />
    

    【讨论】:

    • 谢谢,现在可以了。如您所见,在 onChange 事件中,括号中不需要调用函数,所以我不希望在这里需要它...
    猜你喜欢
    • 2018-02-10
    • 2018-12-14
    • 2018-04-08
    • 2016-06-17
    • 2021-09-25
    • 2019-03-21
    • 2021-10-08
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多