简体   繁体   中英

How to create Dynamic Function Name in ReactJS & use on onBlur?

I want to use Function name whose name is as per concatenating strings and variable.

validate contains the Function Name:

const validate='validate'+type.replace(/^./, type[0].toUpperCase());

where type='email'

const validateEmail = (e) => {
email=e.target.value;
//console.log(email);
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
{(!re.test(email)) && console.log("Please enter a valid email address");}
}

Now I want to use this validate as the function name in onBlur

onBlur={validate}

in

<input onChange={handleChange} onBlur={validate} />

Warning: Expected onBlur listener to be a function, instead got a value of string type.

You can have a generic function like this, which takes type as input and returns a validating function.

const createValidator = type => {
    switch (type) {
        case 'email':
            return (event) => {
                const email = event.target.value;
                const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                (!re.test(email)) && console.log("Please enter a valid email address");
            }

        default:
            return null;
    }
}

And in your input tag, you can use it like this

<input onChange={handleChange} onBlur={createValidator('email')} />

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