iam*_*ynq 5 javascript reactjs react-hooks
据我了解,useImperativeHandle帮助父组件能够调用其子组件的函数。您可以在下面看到一个简单的示例
const Parent = () => {
const ref = useRef(null);
const onClick = () => ref.current.focus();
return <>
<button onClick={onClick} />
<FancyInput ref={ref} />
</>
}
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
Run Code Online (Sandbox Code Playgroud)
但仅使用它就可以轻松实现useRef
const Parent = () => {
const ref = useRef({});
const onClick = () => ref.current.focus();
return <>
<button onClick={onClick} />
<FancyInput ref={ref} />
</>
}
function FancyInput(props, ref) {
const inputRef = useRef();
useEffect(() => {
ref.current.focus = inputRef.current.focus
}, [])
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
Run Code Online (Sandbox Code Playgroud)
那么真正的目的是什么useImperativeHandle。有人可以给我一些建议吗?谢谢
useMemo可能类似于和useCallbackwhere之间的关系useCallback(fn, deps)相当于useMemo(() => fn, deps)。有时实现目标的方法不止一种。
我想说的是,useImperativeHandle代码可以更简洁/干一些当您需要公开多个属性时,
例子:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
property,
anotherProperty,
... etc ...
}), []); // use appropriate dependencies
...
}
Run Code Online (Sandbox Code Playgroud)
与
function FancyInput(props, ref) {
const inputRef = useRef();
useEffect(() => {
ref.current.focus = inputRef.current.focus;
ref.current.property = property;
ref.current.anotherProperty = anotherProperty;
... etc ...
}, []); // use appropriate dependencies
...
}
Run Code Online (Sandbox Code Playgroud)
区别不大,但useImperativeHandle代码更少。
| 归档时间: |
|
| 查看次数: |
594 次 |
| 最近记录: |