简体   繁体   English

将常规函数作为参数传递给JavaScript?

[英]Passing a general function as arguments in JavaScript?

I'm making a form with validation in React.js. 我正在用React.js进行验证的表单。 Is there a way that I can pass a "general" function in as parameters? 有没有一种方法可以将“常规”函数作为参数传递? I have functions that validate each of the inputs in the form. 我具有验证表单中每个输入的函数。 For example, if I have: 例如,如果我有:

updateState(e) {
        if (this.validateEmail(e.target.value) === true) {
            this.setState({[e.target.className]: e.target.value});
            this.setState({errorMsg: 'Valid'});
            document.getElementById(e.target.className).className = "green";
        }
        else if (e.target.value.length === 0) {
            this.setState({errorMsg: 'Empty submission'});
            document.getElementById(e.target.className).className = "red";
        }
        else {
            this.setState({errorMsg: 'Invalid form input'});
            document.getElementById(e.target.className).className = "red";
        }
}

I want to be able to pass in functions such as validateName, validateEmail, validateAddress so it looks like this: 我希望能够传递诸如validateName,validateEmail,validateAddress之类的函数,因此它看起来像这样:

updateState(e, parameterFunction) {
            if (this.parameterFunction(e.target.value) === true) {
                this.setState({[e.target.className]: e.target.value});
                this.setState({errorMsg: 'Valid'});
                document.getElementById(e.target.className).className = "green";
            }
            else if (e.target.value.length === 0) {
                this.setState({errorMsg: 'Empty submission'});
                document.getElementById(e.target.className).className = "red";
            }
            else {
                this.setState({errorMsg: 'Invalid form input'});
                document.getElementById(e.target.className).className = "red";
            }
    }

Is this possible? 这可能吗?

Thanks all, this is my first StackOverflow question! 谢谢,这是我的第一个StackOverflow问题!

Yes, you could do it, but this function is not defined in your this object, it's just like another variable, just call it! 是的,您可以执行此操作,但是此函数未在this对象中定义,就像另一个变量一样,只需调用它即可!

function updateState(e, validateName, validateEmail, validateAddress) {
    var data = e.target.value;

    if (validateName(data.name) && validateEmail(data.mail) && validateAddress(data.address) {
            //Do some stuff
    }
}

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

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