登录页面可以获取页面localStorage的默认值,登录获取输入框的值发送给后台,重置清空输入框的值
1.0 父子通信版本
父组件
import React, { Component } from 'react'
import Field from './components/Field'
import Button from './components/Button'
export default class App extends Component {
state = {
username: 'default value' || localStorage.getItem('username'),
password: ''
}
render() {
return (
<div>
<h2>登录页面</h2>
<Field label="用户名" type="text" onChangeEvent={(value) => { this.setState({ username: value }) }} value={this.state.username} ></Field>
<Field label="密码" type="password" onChangeEvent={(value) => { this.setState({ password: value }) }} value={this.state.password}></Field>
<div style={{ display: 'flex', 'marginLeft': '110px' }}>
<Button type="button" value="登录" event={() => { console.log(this.state.username, this.state.password, '发送后端验证'); }} />
<Button type="button" value="重置" event={() => {
this.setState({ username: '', password: '' })
}} />
</div>
</div>
)
}
}
子组件: 输入框
import React, { Component } from 'react'
export default class Field extends Component {
render() {
return (
<div style={{display: 'flex',margin: '10px'}}>
<label style={{width:'100px',display: 'block'}}>{this.props.label}: </label>
<input style={{ width: '200px', height: '25px', padding: '0px 5px' }} type={this.props.type} onChange={(event) => {
this.props.onChangeEvent(event.target.value)
}} value={this.props.value}/>
</div>
)
}
}
子组件: 按钮
import React, { Component } from 'react'
export default class Button extends Component {
render() {
return (
<div>
<button style={{cursor:'pointer','marginRight':'20px'}} type={this.props.type} onClick={this.props.event} >{this.props.value}</button>
</div>
)
}
}
2.0 ref通信版本
父组件
import React, { Component } from 'react'
import Field from './components/Field-5'
import Button from './components/Button'
export default class App extends Component {
username = React.createRef()
password = React.createRef()
render() {
return (
<div>
<h2>登录页面</h2>
<Field label="用户名" type="text" ref={this.username} ></Field>
<Field label="密码" type="password" ref={this.password} ></Field>
<div style={{ display: 'flex', 'marginLeft': '110px' }}>
<Button type="button" value="登录" event={() => { console.log(this.username.current,this.username.current.state.value,this.password.current.state.value) }} />
<Button type="button" value="重置" event={() => {
this.username.current.clear();
this.password.current.clear();
}} />
</div>
</div>
)
}
}
子组件
import React, { Component } from 'react'
export default class Field extends Component {
state = {
value:''
}
clear() {
this.setState({value:''})
}
render() {
return (
<div style={{display: 'flex',margin: '10px'}}>
<label style={{width:'100px',display: 'block'}}>{this.props.label}: </label>
<input style={{ width: '200px', height: '25px', padding: '0px 5px' }} type={this.props.type} onChange={(event) => {
this.setState({
value: event.target.value
})
}} value={this.state.value}/>
</div>
)
}
}