,
何が問題か
-
typescriptとの連携が難しい
-
parent.child.id
のように文字列でnameを指定するのが難しい(バグを生みやすい)
検証
import { useEffect, useRef } from "react";
type Form = {
[key: string]: { [key: string]: string };
};
const Cell = (props: { obj: { [key: string]: string }; id: string }) => {
return (
<input
onChange={(e) => {
if (!props.obj) {
props.obj = { [props.id]: e.target.value };
} else {
props.obj[props.id] = e.target.value;
}
console.log(props.obj); // --> ここでは{1 : 入力値}になるが
}}
></input>
);
};
const App = () => {
const ref = useRef<Form>({ a: {} });
useEffect(() => {
return () => {
ref.current = { a: {} };
};
}, []);
return (
<>
<Cell id={"1"} obj={ref.current["a"]} />
<button
onClick={() => {
console.log(ref.current); // ここは{a: { 1: 入力値}}にはならず、{a:{}}のまま
}}
>
Print
</button>
</>
);
};
export default App;
-
深い階層から更新するには、ref本体を渡さないといけない
-
objectの子を渡しても、その子は更新されるが、親には伝搬しない
-
結局深いところで更新するには、全体の座標を教えないといけない
parent.child.id