Вла*_*ров 12 reactjs react-forwardref use-ref
我正在尝试使用React.forwardRef()并同时React.useRef()在组件中使用的任务。
问题我只能
使用或使用forwardRef 属性。所以,我不知道如何一起使用它们。示例代码:myOwnRef ref
interface IExampleInputProps {
value: string,
onChange: (event: ChangeEvent<HTMLInputElement>) => void
}
const ExampleInput = forwardRef<HTMLInputElement | null, IExampleInputProps>(({value, onChange}, ref) => { // can't to use "ref" parameter
const myOwnRef = React.useRef<HTMLInputElement | null>(null);
return <input ref={el => {
myOwnRef.current = el; // => OK
if (ref) { // trying to use the ref passed from the forwardRef function
ref.current = el; // => ERROR
}
}} value={value} onChange={onChange}/>
})
Run Code Online (Sandbox Code Playgroud)
hev*_*ev1 18
要在转发引用的同时访问引用,执行以下操作更简单:
useImperativeHandle外部引用(正在转发到的)上的钩子并传递一个返回current内部引用属性的函数,该函数将设置为current外部引用属性的值。import { forwardRef, useImperativeHandle, useRef } from 'react';
const MyComponent = forwardRef<HTMLInputElement, IExampleInputProps>(({value, onChange}, outerRef) => {
const innerRef = useRef<HTMLInputElement>(null);
useImperativeHandle(outerRef, () => innerRef.current!, []);
// remember to list any dependencies of the function that returns the ref value, similar to useEffect
return <input ref={innerRef} value={value} onChange={onChange} />;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5371 次 |
| 最近记录: |