调用具有动态参数类型的函数

时间:2019-04-13 22:45:17

标签: javascript reactjs

如何调用具有不同类型的函数,因为我有时希望使用事件对象来调用它,有时想要使用数组或事件以外的任何东西来调用它

const onChange = (e) => {
    if( e is Event ) { // something like this
        // do some stuff with e.target.value
    } else { // different argument type
        ...
    }
}

使用事件对象调用

<input type="text" onChange={ (e) => onChange(e) } />

使用其他参数类型调用

<input type="checkbox" onChange={ (e) => {
    let newValues;
    // do some calculation
    ...
    onChange(newValues); 
}}/>
...

1 个答案:

答案 0 :(得分:1)

好吧,如果在两种情况下都执行typeof e,您将得到object作为响应,因为事件和数组都是javascript中的对象。

要检测对象是否为数组,您可以使用Array.isArray()

要检测对象是否为DOM事件,可以执行e instanceof Event

在reactjs中,您必须将其更改为e.nativeEvent instanceof Event

因此您可以执行以下操作:

const a = document.getElementById('test');

const onClick = (e) => {
    // use (e.nativeEvent instanceof Event) in reactjs instead
    if(e instanceof Event) { 
        // do some stuff with e.target.value
        console.log("Response: I received an event");
    } else if (Array.isArray(e)) { // it's an array
        console.log("Response: I received an array");
    }
}

a.addEventListener('click', onClick);

console.log('Call the method passing an array');
onClick([2,3,4]);
<div id='test'>click</div>

相关问题