简体   繁体   English

React Js - 无法在输入字段中输入值

[英]React Js - Unable to enter value in Input Field

I appreciate all of your idea in advance.我提前感谢您的所有想法。 My problem here is the input field of the email is not updating.我的问题是 email 的输入字段没有更新。 Can anyone give me a solution?谁能给我一个解决方案?

<input
    type="text"
    placeholder="Enter Email "
    onChange={this.emailHandle}
    value={this.state.email}
/>

Event handler for the above input field is here:上述输入字段的事件处理程序在这里:

emailHandle = (e) => {
    if (e.target.value !== "undefined") {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (pattern.test(e.target.value)) {
            console.log(e.target.value);
            this.setState({ email: e.target.value })
        }
    }
}

The onChange event will never be validate by the regex cause it is called on each key typed. onChange事件永远不会被正则表达式验证,因为它会在每个键入的键上调用。 So you start typing andy@gmail.com , with the a but a does not pass the regex... so the state is not updated... so it's like you didn't type a .所以你开始输入andy@gmail.com ,但a没有a正则表达式......所以 state 没有更新......所以就像你没有输入a

What's the initial value of your component state?您的组件 state 的初始值是多少? For one, if you're not initializing the email property on state to be an empty string, and it's undefined, you're blocking that state from ever updating with your undefined check.一方面,如果您没有将 state 上的 email 属性初始化为空字符串,并且它是未定义的,那么您将使用未定义的检查阻止 state 的更新。 But you have a bigger problem than that.但你有一个比这更大的问题。 You're testing to see if the value of the input matches your email regex pattern.您正在测试输入的值是否与您的 email 正则表达式模式匹配。 That won't ever work if you use that check to block setting state.如果您使用该检查来阻止设置 state,那将永远不会起作用。 onChange is going to fire every time the input value changes, and that means it's going to change one character at a time.每次输入值更改时都会触发onChange ,这意味着它会一次更改一个字符。 So what's happening is the user types a character, the onChange fires, but it doesn't match your pattern, and you don't update state.所以发生的事情是用户键入一个字符, onChange触发,但它与您的模式不匹配,并且您没有更新 state。

What you want to do is always update state and then handle this as validation to block submitting the form.您想要做的是始终更新 state 然后将其作为验证处理以阻止提交表单。 Or you could show an error of some kind, but you need to always call setState with the new value on e.target.value .或者您可以显示某种错误,但您需要始终使用e.target.value上的新值调用setState

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

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