Failed prop type: Invalid prop `onClick` of type `

2019-07-25 18:28发布

问题:

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