【react】forwardRef报错
2023-08-11 本文已影响0人
西叶web
报错
[object Object]: ref
is not a prop. Trying to access it will result in undefined
being returned. If you need to access the same value within the child component, you should pass it as a different prop.
解决
你不该在forwordRef的组件内一开始就打印ref
示例
import { useRef ,forwardRef} from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
// console.log('props, ref: ', props, ref); // 直接打印就会报错
const { label, ...otherProps } = props;
return (
<label>
{label}
<input {...otherProps} ref={ref} />
</label>
);
});
export default function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}