如何检查组件prop是否是React中的函数?

eag*_*ose 3 javascript reactjs

我想将一个函数作为道具传递给组件,并在其render函数中使用它,我似乎在这里缺少了一个关键概念。

例如

index.jsx

render(<MyComponent d={data} showName = {d => d.name + ' ' + d.surname}/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

MyComponent.jsx

class MyComponent extends React.Component {
    render() {
        return <h1>if (typeof this.props.showName === 'function') {
            //call this.props.showName(d)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我希望showName属性是一个函数或一个值,并且组件不需要事先知道它。

编辑2

再次考虑,我认为我将构建一个组件,以便它既可以使用函数也可以使用值作为支撑,但是将它们分开,以便可以更好地验证它们。例如,我要么使用

<MyComponent value="some value"/> 
Run Code Online (Sandbox Code Playgroud)

要么

<MyComponent calculatedValue = {// a function}/>
Run Code Online (Sandbox Code Playgroud)

May*_*kla 5

像这样写:

checkMethod(){
    if(typeof(this.props.showName) === 'function') {
        //call this.props.showName(d);
        return null;
    }else{
        return this.props.showName;
    }    
}

class MyComponent extends React.Component {
    render() {
        return 
            <h1>
                {this.checkMethod()}
            </h1>
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Raz*_*lex 3

https://facebook.github.io/react/docs/typechecking-with-proptypes.html

你可以这样做,如果它不是一个函数,它会告诉你:

     MyComponent.propTypes = {
           showName: React.PropTypes.func.isRequired
     };
Run Code Online (Sandbox Code Playgroud)

这是执行此操作的反应方式;)

编辑:我现在明白了,你可以通过使用参数调用它来对 prop 进行断言,如果断言失败,你就会知道它不是一个函数。在npm上检查这个包,开箱即用很容易

https://www.npmjs.com/package/assert