[英]How to pass function as a prop (function component to function component)
I'm currently trying to make the transition from class to function components.我目前正在尝试从 class 过渡到 function 组件。 I know passing a function between class components involves binding and then add the onClick to the child component.
我知道在 class 组件之间传递 function 涉及绑定,然后将 onClick 添加到子组件。
Below is the code that I have - when I click I am not getting the console log - can someone tell me where I'm going wrong?下面是我的代码——当我点击时我没有得到控制台日志——有人能告诉我哪里出错了吗?
PARENT家长
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
CHILD孩子
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
The name of the prop is onClick
, not handleIsLit
道具的名称是
onClick
,而不是handleIsLit
const Box = (props) => {
return <div onClick={props.onClick} className={`Box ${props.isLit ? 'Box-light' : 'Box-dark'}`}></div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.