【问题标题】:How to get value from Material UI textfield after pressing enter?按下回车后如何从 Material UI 文本字段中获取值?
【发布时间】:2021-05-17 23:05:46
【问题描述】:

无法使用此代码获取输入值。我尝试使用 onKeyUp, onKeyDownonKeyPress 但这些都不起作用,因为没有返回值。通常使用onChange 属性获取值,但它会触发每个输入的新字符。

<TextField
  style={{ margin: 8 }}
  placeholder="Add a task"
  fullWidth
  margin="normal"
  onKeyPress={(e) => {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      // write your functionality here
    }
  }}
/>;

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    使用e.target.value 可以获得输入值。添加e.preventDefault 以避免意外行为:

      const onKeyPress = (e) => {
        if (e.key === "Enter") {
          console.log('Input value', e.target.value);
          e.preventDefault();
        }
      }
    
      <TextField
         ...
         onKeyPress={onKeyPress}/>
    

    Working example

    【讨论】:

    【解决方案2】:

    我认为您可以添加一个 onChange 处理程序。然后您的 Enter 可以随心所欲地使用,例如,提交值。像这样的:

      const [value, setValue] = React.useState<string>()
    
        const handleChangeText = (event: React.ChangeEvent<HTMLInputElement>) => {
          setValue(event.target.value);
        };
    
    
    return (
            <TextField
              style={{ margin: 8 }}
              placeholder="Add a task"
              fullWidth
              margin="normal"
    
              inputProps={{
                onKeyPress: (event) => {
                  if (event.key === "Enter") {
                    // write your functionality here
                    event.preventDefault();
                  }
                },
              }}
    
              onChange={handleChangeText}
            />
    )
    

    【讨论】:

    • 每次输入字符时都会触发onChange。我只想在按下回车键后触发功能。
    【解决方案3】:

    这也是它的工作代码。

    <TextField
                    style={{ margin: 8 }}
                    placeholder="Add a task"
                    fullWidth
                    margin="normal"
    
                    inputProps={{
                      onKeyPress: (event) => {
                        if (event.key === "Enter") {
                          // write your functionality here
                          event.preventDefault();
                        }
                      },
                    }}
    
                  />
    

    【讨论】:

      【解决方案4】:

      实际上,大多数情况下,如果您希望拥有这种行为,您很可能会创建一个表单。所以将TextField 包装在form 中并实现onSubmit 事件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-08
        • 2023-03-21
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        相关资源
        最近更新 更多