![](/img/trans.png)
[英]Using React Hooks to pass props down from a parent to a child function
[英]Passing props from parent to child using hooks
我是新来的反应,我正在尝试将道具从父母 function 传递给孩子。 我传递的参数“square_state”和“setSquare_state”在 useSquare 或 handle_square_click function 中未被识别。我使用以下https://designcode.io/react-hooks-handbook-props作为参考。
const handle_square_click = (props) => {
props.setSquare_state(player)
setGetplayer(true)
}
const useSquare = (square_state, setSquare_state) => {
// Hook for square state management and rendering
return (
<button className="square" onClick={<handle_square_click setSquare_state={setSquare_state}/> }>
{square_state}
</button>
);
}
// ------------------------------------------------------------------
// Board Function
const Board = ({player}) => {
let status = "Next Player : " + player
const [square1_state, setSquare1_state] = useState(1);
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
<useSquare
square_state={square1_state}
setSquare_state={setSquare1_state}
/>
这里有很多问题。
带有use
前缀的函数应该保留给自定义钩子。 如果你有一个返回 React 组件的 function ,你应该遵循 React 标准并给它一个大写的名称,一个不以use
开头的名称 - 例如,你可以调用 square function Square
。
当你传递像这样的道具时
square_state={square1_state} setSquare_state={setSquare1_state}
然后孩子将它们视为 object 的属性,其中 object 是 function 的第一个参数 - 就像您对handle_square_click
所做的那样。 所以
const useSquare = (square_state, setSquare_state) => {
应该
const Square = ({ squareState, setSquareState }) => {
(使用非常常见的 camelCasing 约定)
handle_square_click
是一个普通的 function,不是一个组件,所以onClick={<handle_square_click
没有意义。 在 Square 中声明 function,并在传递onClick
属性时仅引用该 function。 在 Square 中声明 function 以避免传递东西。
点击处理程序尝试引用player
,它不在 scope 中。您需要将其从父级传递下来。 ( setGetplayer
可能也需要传递下来,但它的声明未显示在问题的代码中)
const Board = ({ player }) => {
const [squareState, setSquareState] = useState(1);
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
<Square
squareState={squareState}
setSquareState={setSquareState}
player={player}
/>
和
const Square = ({ squareState, setSquareState, player }) => {
const handleSquareClick = () => {
setSquareState(player);
// setGetplayer(true);
};
return (
<button className="square" onClick={handleSquareClick}>
{squareState}
</button>
);
};
<useSquare
square_state={square1_state}
setSquare_state={setSquare1_state}
/>
这不是如何在 React 或钩子中使用子组件。 您应该以大写字母开头命名您的(自定义)组件,并在组件内部调用挂钩。
因此,作为(我输入此内容时出现的上一个答案),您应该重构代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.