【问题标题】:How do you submit on enter key press in a Chakra-UI input?您如何在 Chakra-UI 输入中按回车键提交?
【发布时间】:2021-08-30 06:14:16
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs chakra-ui


    【解决方案1】:
    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>
    </>
    );
    

    【讨论】:

      【解决方案2】:

      您可以通过 2 种方法实现这一目标:

      • 在您的 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>;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 2014-07-10
        • 1970-01-01
        • 2020-09-17
        • 2011-07-09
        相关资源
        最近更新 更多