本文介绍了道具类型失败:提供给ButtonBase的对象类型无效的道具onClick,预期功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<Fab raised="true" size="small" color="primary" variant="extended"
        onClick={props.Store.fetchFromServer}

this.fetchFromServer = async () => {
await console.log('test')
}

正常工作.

但是当更改为关注

<Fab raised="true" size="small" color="primary" variant="extended"
        onClick={props.Store.fetchFromServer('test')}

this.fetchFromServer = async (val) => {
await console.log(val)
}

抛出以下错误,我想念的是什么?

throw following error, what I am missing?

Failed prop type: Invalid prop `onClick` of type `object` supplied to `ButtonBase`, expected `function`

这并没有太大帮助失败的道具类型:无效的道具onClick提供给按钮"的对象"类型的对象",预期的功能"

推荐答案

之所以失败,是因为一旦将参数传递给函数,就调用它,因此它现在返回一个值(并因此成为).解决此问题的方法是将匿名函数传递给onClick()事件,基本上是将其变为函数:

It is failing because once you pass a parameter to the function, you are calling it, and therefore it is now returning a value (and thus becomes an object). The way to get around this is by passing an anonymous function into the onClick() event like so, basically making it into a function:

onClick={e => props.Store.fetchFromServer('test')}

这是一个测试示例,向您展示以不同方式调用的函数的类型:

Here is a test example to show you the types of functions being called in different ways:

a = function (val) {}
b = async (val) => {
  /* await console.log(val) */
}

console.log(typeof(a))
console.log(typeof(b))
console.log(typeof(a('test1')))
console.log(typeof(b('test2')))
console.log(typeof(() => b('test3')))

这篇关于道具类型失败:提供给ButtonBase的对象类型无效的道具onClick,预期功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:41