在Reaction中使用ForwardRef时,我不能声明自定义属性;这可以用<MyInput ref={ref}></MyInput>
,但我不能像这样向它添加自定义属性:
<MyInput someval={someval} ref={ref}></MyInput>
个
错误是
"某些值不能分配给内部属性(&A;RefAttributes)"
//this is the parent component
export const Recognizer: React.FunctionComponent = () => {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
const [someval, setSomeVal] = useState(1);
return ( <div>
<MyInput someval={someval} ref={ref}></MyInput>
<Button onClick={handleClick}>test</Button>)
};
// child component
const MyInput = forwardRef(function MyInput(prop, ref) {
const inputRef = useRef(null);
useImperativeHandle(
ref,
() => {
return {
focus() {
console.log("calling focus");
inputRef.current.focus();
},
scrollIntoView() {
console.log("calling scroll");
inputRef.current.scrollIntoView();
},
};
},
[]
);
return <div ref={inputRef} />;
});
export default MyInput;