微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何停止内部onClick事件传播到React中的外部onSubmit事件?

如何解决如何停止内部onClick事件传播到React中的外部onSubmit事件?

我有一个React应用程序,可以从Unsplash api检索数据。为了从此api请求数据,我实现了具有多个输入字段和按钮的表单。

在我的输入字段旁边,我创建了一个按钮,并在clearInputField事件上传递了函数onClick,单击即可清除输入字段的值。但是,在此实现之后,该事件开始冒泡并触发我在表单上遇到的onSubmit事件。为了防止这种行为,我在e.preventDefault() 函数中传递了clearInputField

现在,一切正常,但如果要触发表单提交,则不能使用ENTER键。取而代之的是,ENTER键现在可以触发clearInputField 功能

在给定的情况下,我如何保留clearInputField函数功能并同时使ENTER键触发onSubmit事件?

export const SearchImages = (props) => {
  const [query,setQuery] = useState("");
  const [images,setimages] = useState([]);
  const [imagesTotal,setimagesTotal] = useState(0);
  const [inputError,setInputError] = useState(false);
  const [noresultsError,setnoresultsError] = useState(false);
  const [excessInputError,setExcessInputError] = useState(false);
  const [topLoader,setTopLoader] = useState(false);
  const [bottomloader,setBottomloader] = useState(false);
  const focusOnSearch = useRef(null);


  const handleSubmit = (e) => {
    if (query.length === 0) {
      e.preventDefault();
      setInputError(true);
    } else if (query.length > 50) {
      e.preventDefault();
      setInputError(false);
      setExcessInputError(true);
    } else {
      setInputError(false);
      setExcessInputError(false);
      setTopLoader(true);
      searchPhotos(e);
      props.addSavedQuery(query);
    }
  };


  const searchPhotos = async (e) => {
    e.preventDefault();
    setnoresultsError(false);
    UnsplashAccessKey.search
      .photos(query,1,10)
      .then(toJson)
      .then((json) => {
        setTopLoader(false);
        setimagesTotal(json.total);
        if (json.results <= 0) {
          setnoresultsError(true);
        } else {
          setimages(json.results);
        }
      });
  };

  const clearInputField = (e) => {
    e.preventDefault();
    setQuery("");
    stopPropagation(e);
  };

  return (
      <form className="search-form" onSubmit={handleSubmit}>
        <div className="search-form__input--wrapper">
          <input
            type="text"
            name="query"
            placeholder='Use keywords,ex: "phone"'
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            ref={focusOnSearch}
            className="search-form__input"
          />
          <button className="search-form__btn--clear" onClick={clearInputField}>
            &#88;
          </button>
        </div>

        <button type="submit" className="search-form__btn--submit">
          Search
        </button>
        <span
          className="search-form__warning"
          style={
            inputError || excessInputError
              ? { display: "block" }
              : { display: "none" }
          }>
          {inputError
            ? "The search field should not stay empty!"
            : "" || excessInputError
            ? "50 characters max length exceeded. Use concise keywords. This is not a poetry app!"
            : ""}
        </span>
      </form>
}

解决方法

尝试添加type="button"

<button className="search-form__btn--clear" type="button" onClick={clearInputField}>
  &#88;
</button>
,

使用事件的stopPropagation方法。

e.stopPropagation();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。