1、登录组件
import { Component } from "react";
import withSubscription from './Hoc'
class Login extends Component {
constructor(props){
super(props)
this.state = {
}
}
render(){
let {state,handleChange,submit1} = this.props;
return(
<div>
<form action="">
用户名:<input type="text" name="username" value={state.username} onChange={handleChange}/>
<br />
密码:<input type="password" name="password" value={state.password} onChange={handleChange}/>
<br />
<button onClick={submit1}>登录</button>
</form>
</div>
)
}
}
export default withSubscription('登录',Login)
2、注册组件
import { Component } from "react";
import withSubscription from './Hoc'
class Register extends Component {
constructor(props){
super(props)
this.state = {
}
}
render(){
let {state,handleChange,submit1} = this.props;
return(
<div>
<form action="">
用户名:<input type="text" name="username" value={state.username} onChange={handleChange}/>
<br />
密码:<input type="password" name="password" value={state.password} onChange={handleChange}/>
<br />
确认密码:<input type="text" name="oPassword" value={state.oPassword} onChange={handleChange}/>
<br />
<button onClick={submit1}>注册</button>
</form>
</div>
)
}
}
export default withSubscription('注册',Register)
3.封装的高阶组件
import React from 'react'
//高阶函数
function withSubscription(type,WarppedComponent) {
//返回一个新的组件
//return 组件
//return
class newComponment extends React.Component {
constructor() {
super()
this.state = {
username: '',
password: '',
oPassword: ''
}
}
//放公共逻辑
//input框被改变
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
submit1 = (e) => {
//阻止默认事件
e.preventDefault();
//判断是登录还是注册
if(type=== '登录'){
console.log(`账号为:${this.state.username} 密码为:${this.state.password}`);
}else if(type=== '注册'){
console.log(`账号为:${this.state.username} 密码为:${this.state.password} 确认密码:${this.state.oPassword}`);
}
}
render() {
let methods = {
handleChange:this.handleChange,
submit1:this.submit1
}
return (
<div>
<h1>{type}</h1>
{/* <WarppedComponent state = { this.state } handleChange = { this.handleChange } submit1 = { this.submit1 }></WarppedComponent> */}
<WarppedComponent state={this.state} {...methods}></WarppedComponent>
</div>
)
}
}
return newComponment
}
export default withSubscription