简体   繁体   English

如何将 function 作为道具传递(功能组件到 function 组件)

[英]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>
}

you shouldn't pass the funtion by onClick.您不应该通过 onClick 传递该功能。 Here a sandbox这里是一个沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM