我的标题似乎没有多大意义,让我尝试解释一下。我有一个GameContainer包含一个ButtonContainer组件的组件。现在我ButtonContainer返回两个按钮,X 和 Y。我正在传递一个函数 foo 例如,现在在我的 Game.js 文件中我将按钮函数作为 props ( (e) => playGame(e)) 传递。我需要事件目标 id 来查看用户是否按下了 X 或 Y。我遇到的问题是当我执行以下代码时undefined返回。游戏.jsconst playGame = (e) => { console.log(e.target.id);}return ( <GameContainer buttonFn={(e) => playGame(e)} />);游戏容器.jsreturn ( <> <p>Game name</p> <ButtonContainer buttonFn={buttonFn} /> </>);ButtonContainer.jsreturn ( <> <button onClick={buttonFn}>X</button> <button onClick={buttonFn}>Y</button> </>);我可以使用 redux,然后将状态传递给我的 Game.js,但我觉得有一种更简单的方法可以做到这一点。e.target.id 在我的 Game.js 中运行良好,但是当我决定将代码拆分为可重用组件并使用 props 时,它返回 undefined。感谢任何帮助希望我的解释有意义。
1 回答

SMILET
TA贡献1796条经验 获得超4个赞
为按钮添加value和。id
export default function App() {
const playGame = (e) => {
console.log(e.target.id);
};
return <GameContainer buttonFn={(e) => playGame(e)} />;
}
function GameContainer({ buttonFn }) {
return (
<>
<p>Game name</p>
<ButtonContainer buttonFn={buttonFn} />
</>
);
}
function ButtonContainer({ buttonFn }) {
return (
<>
<button id="btn-1" value="btn-1" onClick={buttonFn}>
X
</button>
<button id="btn-2" value="btn-2" onClick={buttonFn}>
Y
</button>
</>
);
}
代码 - https://codesandbox.io/s/old-cloud-0deig?file=/src/App.js:51-592
添加回答
举报
0/150
提交
取消