我正在创建一个简单的客户端登录表单。当用户登录状态时,currentAdmin更改为true(默认情况下为false)。由于某种原因,setState引发警告组件正在更改类型为受控的不受控制的输入。输入元素不应从不受控制切换为受控制(反之亦然)。在组件的生命周期中决定使用受控还是不受控制的输入元素。
我尝试在Header.js中使用引用,但这无济于事。
App.js
import React, { Component } from 'react';
import Header from '../Header/Header';
class App extends Component {
constructor(props) {
super(props)
this.state = {
currentAdmin: false
}
}
onSignIn = (login, password) => {
if (login === 'admin' && password === '123') {
this.setState({
currentAdmin: true
})
}
}
onSignout = () => {
this.setState({
currentAdmin: false,
})
}
render() {
return (
<div>
<Header
onSignin={this.onSignIn.bind(this)}
onSignout={this.onSignout.bind(this)}
currentAdmin={this.state.currentAdmin}
/>
</div>
)
}
}
export default App.js;
Header.js
import React, {Component} from 'react';
import './Header.css';
class Header extends Component {
constructor(props) {
super(props);
this.handleSignin = this.handleSignin.bind(this);
this.handleSignout = this.handleSignout.bind(this);
}
handleSignin(e) {
e.preventDefault();
let login = this.refs.login.value;
let password = this.refs.password.value;
this.props.onSignin(login, password);
}
handleSignout(e) {
e.preventDefault();
this.props.onSignout();
}
render() {
if (this.props.currentAdmin === false) {
return (
<div className='header'>
<a href='google.com' className='logo'>ToDoApp</a>
<form className='login' onSubmit={this.handleSignin}>
<input type='text' placeholder='login' ref='login'/>
<input type='password' placeholder='password' ref='password'/>
<input type='submit' value='Log in'/>
</form>
</div>
);
} else {
return (
<div className='header'>
<a href='google.com' className='logo'>ToDoApp</a>
<form className='login' onSubmit={this.handleSignout}>
<input type='submit' value='Log out'/>
</form>
</div>
);
}
}
}
export default Header;
这会引发警告。
答案 0 :(得分:0)
您需要在module initialization error: TypeError
at Object.<anonymous> (/var/task/index.js:6:12)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
上使用defaultValue
属性,而不是input
。检查文档here。
其他选择-您可能希望将value
替换为input type="submit"
答案 1 :(得分:0)
ALexand Tovmach提供了完美的答案(对我个人而言)。我应该将<input type='submit' value='Log in/>
更改为<button type='submit'>Log in</button>