繁体   English   中英

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

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

我正在用React.js进行验证的表单。 有没有一种方法可以将“常规”函数作为参数传递? 我具有验证表单中每个输入的函数。 例如,如果我有:

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";
        }
}

我希望能够传递诸如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";
            }
    }

这可能吗?

谢谢,这是我的第一个StackOverflow问题!

是的,您可以执行此操作,但是此函数未在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