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

天涯浪子 提交于 2019-12-24 15:41:59

问题


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

and

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

works fine.

But when changed to following

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

and

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`

this did not help much Failed prop type: Invalid prop `onClick` of type `object` supplied to `Button`, expected `function`


回答1:


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')))


来源:https://stackoverflow.com/questions/55526271/failed-prop-type-invalid-prop-onclick-of-type-object-supplied-to-buttonbas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!