您如何在 Chakra-UI 输入中按回车键提交?

How do you submit on enter key press in a Chakra-UI input?

我正在创建一个包含输入的组件,该输入可在用户按回车键或单击搜索按钮时将其引导至新选项卡。搜索按钮功能正常,但是我无法获取输入以在按下回车键时调用 handleSubmit 方法。截至目前,按回车键什么都不做。我怎样才能做到这一点? 代码:

  const LinkCard = (props) => {
  const [searchInput, setSearchInput] = useState("");
  const handleChange = (e) => {
    setSearchInput(e.target.value);
  };
  const handleClick = (e) => {
    e.preventDefault();
    location.assign("http://www.mozilla.org");
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    location.assign("http://www.mozilla.org");
  };

  return (
    <Flex borderWidth="1px" borderRadius="lg" alignItems="center">
      {props.icon}
      <Box>{props.websiteName}</Box>
      <InputGroup>
        <Input
          placeholder={"Search " + props.websiteName}
          onChange={handleChange}
          onSubmit={handleSubmit}
          flexGrow="1"
          m="2%"
        />
        <Link href={props.url} passHref={true}>
          <a>
            <InputRightElement m="2%">
              <Button onClick={handleClick}>
                <FaSearch />
              </Button>
            </InputRightElement>
          </a>
        </Link>
      </InputGroup>
    </Flex>
  );
};

有两种可能的方法可以实现:

  • 在您的 submitHandler 上添加一个关键侦听器:
const handleSubmit = e => {
  e.preventDefault();
  if (e.key === "Enter") {
    location.assign("http://www.mozilla.org");
  }
};
  • 在您的输入周围加上 form 并添加提交事件:
<form onSubmit={handleSubmit}>
  <Input
    placeholder={"Search " + props.websiteName}
    onChange={handleChange}
    onSubmit={handleSubmit}
    flexGrow="1"
    m="2%"
  />
</form>;
const [value, setValue] = React.useState('');
return (
<form
  onSubmit={e=> {
    e.preventDefault();
    location.assign('?wd=' + value)
  }}>
  <input value={value} onChange={(e)=> setValue(e.currentTarget.value)} />
  <button type="submit">Search</button>
</form>
)

const [value, setValue] = React.useState('');

return (
<>
  <input 
     value={value} 
     onChange={(e)=> setValue(e.currentTarget.value)} 
     onKeyPress={e=> {
        if (e.key === 'Enter') {
           location.assign('?wd=' + value)
        }
     }}
  />
  <button onClick={()=> location.assign('?wd=' + value)}>Search</button>
</>
);