gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:57:22 24 4
gpt4 key购买 nike

我在 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>
)
}
}

当我使用浏览器自动完成功能时(我不输入“admin”,而是只输入“a”,然后让浏览器填充其余部分),组件的状态不会更新,并且会提交错误的值。当我手动输入用户名/密码时,它可以正常工作。我怎样才能解决这个问题?这是非常常见的用例...

最佳答案

看起来有些browsers have a bug .

您可以尝试使用Autofill polyfill来解决这个问题:

A polyfill to fire a change event when the browser auto fills form fields

关于javascript - 当浏览器自动完成用户名时,React.js 组件的状态不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42380079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com