我目前正在尝试从类组件过渡到功能组件。我知道在类组件之间传递函数涉及绑定,然后将onClick添加到子组件。
下面是我拥有的代码-当我单击时我没有得到控制台日志-有人可以告诉我我要去哪里了吗
父母
import React, { useState } from 'react'
import Box from './Box'
import './GameBoard.css'
import { v4 as uuidv4 } from 'uuid'
function GameBoard() {
const randLit = () => (Math.floor(Math.random() * 2)) === 1
const [gameBoard, setGameBoard] = useState([...new Array(25)].map(box => randLit()))
const handleIsLit = (evt) => {
console.log('working')
}
return (
<div className="GameBoard">
{gameBoard.map((box, idx) => <Box isLit={box} key={uuidv4()} onClick={handleIsLit} />)}
</div>
)
}
export default GameBoard
儿童
import React from 'react'
import './Box.css'
const Box = (props) => {
return <div onClick={props.handleIsLit} className={`Box ${props.isLit ? 'Box-light' : 'Box-dark'}`}></div>
}
export default Box
答案 0 :(得分:1)
道具的名称是onClick
,而不是handleIsLit
const Box = (props) => {
return <div onClick={props.onClick} className={`Box ${props.isLit ? 'Box-light' : 'Box-dark'}`}></div>
}
答案 1 :(得分:0)
您不应通过onClick传递功能。这里是sandbox