简体   繁体   English

带参数调用多个函数

[英]Call multiple function with parameters

I have a function with parameter that is pass as a property:我有一个带有作为属性传递的参数的函数:

 currentTaskID = null;
 setTaskID = (id) => { 
         this.currentTaskID = id;
         console.log(this.currentTaskID);
         console.log("test");
     }

Then on my other component I have a function that needs the event handler and call the prop function when clicked:然后在我的另一个组件上,我有一个需要事件处理程序并在单击时调用 prop 函数的函数:

// select/open task
    openTask = (event) => {
        let targetClass = event.target.classList; 
        if(targetClass.contains('active'))
            targetClass.remove('active')
        else
            targetClass.add('active') 
    }

    // onClick trigger multiple functions
    funcWrapper = (id) => {
        this.openTask();
        this.props.setTaskID.bind(this, id)
    }

Onclick:点击:

onClick={funcWrapper(id)}

error:错误:

Cannot read property 'target' of undefined

How can I pass parameters without overwriting the event?如何在不覆盖事件的情况下传递参数?

As the error suggested Cannot read property 'target' of undefined .由于错误提示无法读取 undefined 的属性 'target' It is not able to find the target property in undefined .它无法在undefined 中找到target属性。 Because target is a property of event object.因为targetevent对象的一个​​属性。 Because event has not been passed to the method it is represented with undefined.因为event尚未传递给方法,所以它用 undefined 表示。

I suppose you have to do the call in a anonymous callback:我想你必须在匿名回调中进行调用:

onClick={e => funcWrapper(e, id)}

Then pass the event to the method:然后将事件传递给方法:

funcWrapper = (ev, id) => {
    this.openTask(ev);
    this.props.setTaskID(id); // <---as it is in fat arrow syntax no need for bind
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM