简体   繁体   中英

Passing a general function as arguments in JavaScript?

I'm making a form with validation in 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:

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!

Yes, you could do it, but this function is not defined in your this object, it's just like another variable, just call it!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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