Javascript 事件返回未定义,试图通过组件传递它

Javascript 事件返回未定义,试图通过组件传递它,javascript,reactjs,Javascript,Reactjs,我的标题似乎没有多大意义,让我试着解释一下 我有一个GameContainer组件,其中包括一个ButtonContainer组件 现在我的ButtonContainer返回两个按钮,X和Y。我正在传递一个函数foo,例如,现在在我的Game.js文件中,我将按钮函数作为道具传递((e)=>playGame(e))。我需要事件目标id来查看用户是否按了X或Y 我遇到的问题是,当我执行下面的代码时,返回的是undefined Game.js const playGame = (e) => {

我的标题似乎没有多大意义,让我试着解释一下

我有一个
GameContainer
组件,其中包括一个
ButtonContainer
组件

现在我的
ButtonContainer
返回两个按钮,X和Y。我正在传递一个函数foo,例如,现在在我的Game.js文件中,我将按钮函数作为道具传递(
(e)=>playGame(e)
)。我需要事件目标id来查看用户是否按了X或Y

我遇到的问题是,当我执行下面的代码时,返回的是
undefined

Game.js

const playGame = (e) => {
   console.log(e.target.id);
}
return (
   <GameContainer buttonFn={(e) => playGame(e)} />
);
const playGame=(e)=>{
console.log(e.target.id);
}
返回(
游戏(e)}/>
);
GameContainer.js

return (
  <>
    <p>Game name</p>
    <ButtonContainer buttonFn={buttonFn} />
  </>
);
return (
  <>
    <button onClick={buttonFn}>X</button>
    <button onClick={buttonFn}>Y</button>
  </>
);
返回(
游戏名称

);
ButtonContainer.js

return (
  <>
    <p>Game name</p>
    <ButtonContainer buttonFn={buttonFn} />
  </>
);
return (
  <>
    <button onClick={buttonFn}>X</button>
    <button onClick={buttonFn}>Y</button>
  </>
);
返回(
X
Y
);
我可以使用redux,然后将状态传递给我的Game.js,但我觉得有一种更简单的方法可以做到这一点。e、 target.id在我的Game.js中运行良好,但当我决定将代码拆分为可重用组件并使用道具时,它返回未定义的


感谢您的帮助,希望我的解释有意义。

为按钮添加
值和
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>
    </>
  );
}
导出默认函数App(){
康斯特游戏=(e)=>{
console.log(e.target.id);
};
返回游戏(e)}/>;
}
函数GameContainer({buttonFn}){
返回(
游戏名称

); } 函数ButtonContainer({buttonFn}){ 返回( X Y ); }

代码-

请在此处重现此问题-当您单击一个按钮调用playtGame函数时?未定义的错误在哪里?是的,当按下调用console.log(e.target.id)的按钮时,它返回未定义的。我忘了将值属性添加到按钮中。。。请在@UKS上发表评论,这样我就可以接受你的回答,因为你是第一个