猿问

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

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


我有一个GameContainer包含一个ButtonContainer组件的组件。


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


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


游戏.js


const playGame = (e) => {

   console.log(e.target.id);

}

return (

   <GameContainer buttonFn={(e) => playGame(e)} />

);

游戏容器.js


return (

  <>

    <p>Game name</p>

    <ButtonContainer buttonFn={buttonFn} />

  </>

);

ButtonContainer.js


return (

  <>

    <button onClick={buttonFn}>X</button>

    <button onClick={buttonFn}>Y</button>

  </>

);

我可以使用 redux,然后将状态传递给我的 Game.js,但我觉得有一种更简单的方法可以做到这一点。e.target.id 在我的 Game.js 中运行良好,但是当我决定将代码拆分为可重用组件并使用 props 时,它返回 undefined。


感谢任何帮助希望我的解释有意义。


千巷猫影
浏览 167回答 1
1回答

SMILET

为按钮添加value和。idexport default function App() {&nbsp; const playGame = (e) => {&nbsp; &nbsp; console.log(e.target.id);&nbsp; };&nbsp; return <GameContainer buttonFn={(e) => playGame(e)} />;}function GameContainer({ buttonFn }) {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <p>Game name</p>&nbsp; &nbsp; &nbsp; <ButtonContainer buttonFn={buttonFn} />&nbsp; &nbsp; </>&nbsp; );}function ButtonContainer({ buttonFn }) {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <button id="btn-1" value="btn-1" onClick={buttonFn}>&nbsp; &nbsp; &nbsp; &nbsp; X&nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; <button id="btn-2" value="btn-2" onClick={buttonFn}>&nbsp; &nbsp; &nbsp; &nbsp; Y&nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; </>&nbsp; );}代码 - https://codesandbox.io/s/old-cloud-0deig?file=/src/App.js:51-592
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答