React高階元件(表單)應用回顧
阿新 • • 發佈:2019-01-01
1. 首先介紹函數語言程式設計:
function hello(){
console.log('大家好,我是harry!')
}
function getWord(fn){
return function(){
console.log('大家好,我是林宇航');
fn();
console.log('大家好,我是豬豬俠')
}
}
let h = getWord(hello);
h();
//列印結果:
大家好,我是林宇航
大家好,我是harry!
大家好,我是豬豬俠
2. 高階元件的定義:
就是一個函式,這個函式傳入一個元件,然後返回一個新的元件;為了程式碼的複用性,減少程式碼的冗餘;“ 所謂的元件本質上都是函式 ”
2-1. 高階元件屬性代理:
(1)普通高階元件寫法
class Hello extends Component{ render(){ return ( <h3> 深圳,你好! </h3> ) } } function WrapperHello(Comp){ class WrapComp extends Component{ render(){ return ( <div> <h3> 高階元件,你好! </h3> <Comp {...this.props}></Comp> </div> ) } } return WrapComp; } Hello = WrapperHello(Hello); <Hello></Hello> //結果: 高階元件,你好! 深圳,你好!
(2)ES7 裝飾器寫法:
function WrapperHello(Comp){ class WrapComp extends Component{ render(){ return ( <div> <h3> 高階元件,你好! </h3> <Comp {...this.props}></Comp> </div> ) } } return WrapComp; } @WrapperHello class Hello extends Component{ render(){ return ( <h3> 深圳,你好! </h3> ) } } //結果: 高階元件,你好! 深圳,你好!
3. 高階元件反向繼承
function WrapperHello(Comp){
class WrapComp extends Comp{
componentDidMount(){
//進行載入完成後的處理
console.log('高階元件載入完成!');
}
render(){
return (
<div>
<Comp {...this.props}></Comp>
</div>
)
}
}
return WrapComp;
}
@WrapperHello
class Hello extends Component{
render(){
return ( <h3> 深圳,你好! </h3> )
}
}
<Hello></Hello>
4. 登入註冊高階元件封裝
export default function LRForm(Comp){
return class WrapFromComp extends Component{
constructor(props){
super(props);
this.state = {};
}
handleChange = (k,v)=>{
console.log(k,v);
this.setState({
[k]: v
})
}
render(){
return (
<div>
<Comp {...this.props} handleChange={this.handleChange} state={this.state}></Comp>
</div>
);
}
}
}
5. 表單資料封裝的高階元件呼叫:
import LRForm from ‘@/component/form/form.js';
@LRForm
class Login extends Component{
//…
}
@LRForm
class Register extends Component{
//…
}