[英]React.forwardRef - get value from child component
想象一下我們有這樣的代碼:
const InputComponent = React.forwardRef((props, ref) => {
// I need to access ref.current?.value... here
return <input ref={ref} {...props} />
})
const Parent = () => {
const inputRef = useRef()
return <InputComponent ref={ref} />
}
這種技術似乎是不可能的? InputComponent 中的typeof ref
是InputComponent
但無法調用。 我可以從InputComponent
訪問值嗎?
除了拼寫錯誤,您的代碼應該可以工作,唯一需要注意的是,您在第一次渲染時沒有 ref,因此可選鏈接current?.value
。
而且因為它是一個 ref,改變輸入值不會觸發渲染,所以要調試它的值,你需要手動觸發它。
import "./styles.css";
import React, { useReducer, useRef } from "react";
const InputComponent = React.forwardRef((props, ref) => {
console.log(ref.current?.value);
return <input ref={ref} {...props} />;
});
const Parent = () => {
const inputRef = useRef();
const [, render] = useReducer((p) => !p, false);
return (
<>
<InputComponent ref={inputRef} />
<button onClick={render}>trigger render to see ref value</button>
</>
);
};
export default function App() {
return <Parent />;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.