首页 > 解决方案 > 是否可以将 id/ 字符串传递给 onFocus 事件?

问题描述

是否可以将密钥/ID 传递给 onFocus 事件?

这是我的代码:

  handleChange: (e: SyntheticEvent<FormInputElements>) => void,
  handleFocus: (e: SyntheticEvent<FormInputElements>) => void,

  const handleEvent = (event?: EventListener, inputvalue: string) => {
    if (event) {
      return event(component, inputvalue);
    }
    return null;
  };

  const handleChange = (e: SyntheticEvent<FormInputElements>) => {
    handleEvent(onChange, e.currentTarget.value);

    if (hasFocus && showErrors) {
      setResolvedErrors(true);
      handleFocus(component.key);
    }
  };

  const handleFocus = (e: SyntheticEvent<FormInputElements>) => {
    setHasFocus(true);
    handleEvent(onFocus, e.currentTarget.value);
  };

基本上,在我的handleChange事件中——如果运行了 if 语句——我想运行该handleFocus事件——但是将我的组件的键传递给它,以便它专注于正确的元素?

标签: javascriptreactjseventsonfocus

解决方案


您可以为此目的使用useRef挂钩。

看看给定的例子:

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}


推荐阅读