Javascript 在React中的组件构造函数中传递函数

Javascript 在React中的组件构造函数中传递函数,javascript,reactjs,function,Javascript,Reactjs,Function,一个关于我正在开发的蛇游戏的问题 我读过关于在构造函数中设置函数的内容。现在举个例子,我希望snakeMoves函数调用foodGenerator,它在构造函数中,但不在状态中,所以调用这个。snakeMoves中的状态不会得到foodGenerator 我必须通过哪些选项将foodGenerator传递给snakeMoves class Play extends Component { constructor(props) { super(pr

一个关于我正在开发的蛇游戏的问题

我读过关于在构造函数中设置函数的内容。现在举个例子,我希望snakeMoves函数调用foodGenerator,它在构造函数中,但不在状态中,所以调用这个。snakeMoves中的状态不会得到foodGenerator

我必须通过哪些选项将foodGenerator传递给snakeMoves

 class Play extends Component {
            constructor(props) {
            super(props)
            this.state ={
                gameSqueres: [],
                food: null
            }

            this.foodGenerator = this.foodGenerator.bind(this)
        }

    componentDidMount() {
            // create food
            this.foodGenerator()
        }

    foodGenerator() {
        console.log('food')
    }

    // snake move system
    snakeMoves = (e) => {
        const { gameSqueres } = this.state;
        console.log(foodGenerator())
    } 

如果需求只是绑定此并获得一个新函数,则可以使用箭头函数。从方法
snakeMoves()
,只需调用:
this.foodGenerator()


使用此访问类方法

snakeMoves = (e) => {
    const { gameSqueres } = this.state;
    console.log(this.foodGenerator())
} 

您可以简单地执行以下操作:

// snake move system
snakeMoves = (e) => {
   this.foodGenerator();
} 

不需要行
this.foodGenerator=this.foodGenerator.bind(this)
。只需将
foodGenerator
作为一个箭头函数,并使用
this.foodGenerator()
好的,我现在看到它正在工作,但如何避免在foodGenerator执行时返回“undefined”?@Bizzaros:AFIK javascript总是在语句执行时返回一些内容,如果某个特定的statent不返回任何内容,ut将返回
未定义的
。在
snakeMoves()
下,无需执行
console.log(this.foodGenerator())
,只需执行
this.foodGenerator()
。或者,如果要在snakeMoves中执行控制台登录,则从
foodGenerator
返回一个值,而不是将其记录在那里
// snake move system
snakeMoves = (e) => {
   this.foodGenerator();
}