是否可以将密钥/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
事件-但传递我的组件的密钥,以便它关注正确的元素?
您可以使用useRef hook来实现此目的。
看一下给出的例子:
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>
</>
);
}