🍛
Reactコンポーネントで高階関数+部分適用を使おう!
はじめに
- Reactでコンポーネントを書くときに、return文の中に式が入ってしまう
結論
これが↓
const Sample = () => {
const [text, setText] = useState<string>("");
return (
<>
<input
value={text}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setText(e.target.value)
}
/>
<button onClick={() => console.log(text)}>click</button>
</>
);
};
こう↓
const Sample = () => {
const [text, setText] = useState<string>("");
const handleClick = (text: string) => () => console.log(text);
const handleInput = (e: React.ChangeEvent<HTMLInputElement>) =>
setText(e.target.value);
return (
<>
<input value={text} onChange={handleInput} />
<button onClick={handleClick(text)}>click</button>
</>
);
};
Discussion