首页 > 解决方案 > 您如何在 Chakra-UI 输入中按 Enter 键提交?

问题描述

我正在创建一个包含输入的组件,该输入在按下回车键或单击搜索按钮时将用户引导至新选项卡。搜索按钮功能正常,但是我无法获取输入以在输入键按下时调用 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>
  );
};

标签: javascriptreactjschakra-ui

解决方案


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>
</>
);

推荐阅读