如何将10传递给增量计数器num?
我想知道这个参数是如何传递的,因为我看不太清楚
const Button = React.memo(function Button({ incrementButton }) {
return <button onClick={() => incrementButton(10)}>+</button>;
});
Button.propTypes = {
incrementButton: P.func,
};
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = useCallback((num) => {
setCounter((c) => c + num);
}, []);
const btn = useMemo(() => {
return <Button incrementButton={incrementCounter} />;
}, [incrementCounter])
return (
<div className="App">
<p>Teste</p>
<h1>C1: {counter}</h1>
{btn}
</div>
);
}
不确定它是否对你有帮助:
const Button = React.memo(function Button({ incrementButton }) { // 2) so here incrementButton = incrementCounter
return <button onClick={() => incrementButton(10)}>+</button>; // 3) here 10 is passed inside incrementButton which is incrementCounter
});
Button.propTypes = {
incrementButton: P.func,
};
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = useCallback((num) => { // 4) so here num is the 10 that was passed on 3 step.
setCounter((c) => c + num); // 5) here counter get updated using setState callback with previous value: (0) => 0 + 10;
}, []);
const btn = useMemo(() => {
return <Button incrementButton={incrementCounter} />; // 1) here incrementButton = incrementCounter
}, [incrementCounter])
return (
<div className="App">
<p>Teste</p>
<h1>C1: {counter}</h1>
{btn}
</div>
);
}