简体   繁体   English

浏览器自动完成用户名时,React.js组件的状态不会更新

[英]State of React.js component is not updated when browser auto-completes username

I have the following component in React: 我在React中有以下组件:

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {username: '', password: '', redirectToReferrer: false};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const value = event.target.value;
    const name = event.target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log('A name was submitted: ' + this.state.username);
    Auth.authenticate(this.state.username, this.state.password, () => {
      this.setState({ redirectToReferrer: true })
    })
  }

  render() {
    const { from } = this.props.location.state || { from: { pathname: '/' } }
    const { redirectToReferrer } = this.state

    if (redirectToReferrer) {
      return (
        <Redirect to={from}/>
      )
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <form id='loginForm'>
          <input type="text" name="username" onChange={this.handleChange} />
          <input type="password" name="password" onChange={this.handleChange} />
          <button onClick={this.handleSubmit}>Log in</button>
        </form>
      </div>
    )
  }
}

When I use the browser auto-complete feature (instead of typing 'admin' I type just 'a' and let browser to fill the rest) the component's state is not update and it submits incorrect value. 当我使用浏览器自动完成功能(而不是键入“ admin”时,我仅键入“ a”并让浏览器填充其余部分)时,组件的状态未更新,并且提交了错误的值。 When I type the username/password all by hand it works correctly. 当我全部手动输入用户名/密码时,它可以正常工作。 How can I fix this? 我怎样才能解决这个问题? It's pretty common use case... 这是很常见的用例...

It looks like that some browsers have a bug . 看起来有些浏览器有错误

You can try to workaround it with Autofill polyfill : 您可以尝试使用自动填充polyfill解决它:

A polyfill to fire a change event when the browser auto fills form fields 当浏览器自动填充表单字段时,将触发更改事件的polyfill

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

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