javascript - 是否可以将 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
事件——但是将我的组件的键传递给它,以便它专注于正确的元素?
解决方案
您可以为此目的使用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>
</>
);
}
推荐阅读
- javascript - Bootstrap Modal - 无法从relatedTarget 收集属性?
- ajax - TYPO3 Fluidcontent - 通过 pagenum 加载页面
- python - 调试时如何检查 Django 生成的原始 SQL 查询?
- android - 如何在 Firebase 中没有键的情况下将新数据插入数组
- javascript - Electron 修改 .asar 中的文件存储
- python - Python - 如果参数中的语句?
- swift - 从 CGImage 获取像素信息并使用 Swift 4 进行更改
- sql - 一个 SQL 函数调用中的多个 ALTER TABLE ADD COLUMN
- vb.net - DefaultCellStyle.Format 在单元格中输入数据后不起作用
- python - 在 Python3 中查找和替换字符