属性代理:
1.操作props:
高阶组件:
import React , {Component } from 'react';
const wrapComponent = (TempComponent) => class extends Component{
handleClick(){
('click')
}
render(){
return(
<TempComponent {...} handleClick={}/>
)
}
}
export default wrapComponent;
应用:
import React, { Component } from 'react';;
import LifeCircle from './test/';
import wrapComponent from './example/'
const WrapedComponent = wrapComponent(LifeCircle)
class App extends Component {
render() {
return (
<div className="App">
<WrapedComponent hello="hello world"/>
</div>
);
}
}
export default App;
2.refs获取组件实例:
高阶组件获取refs:
import React , {Component } from 'react';
const wrapComponent = (TempComponent) => class extends Component{
componentDidMount(){
()
}
render(){
return(
<TempComponent ref='childComponent' {...} />
)
}
}
export default wrapComponent;
3.抽离state:
要抽离state的组件:
import React,{Component } from 'react';
export default class Login extends Component {
render(){
return (
<div>
<div>
<label >账户</label>
<input type="text" name="username" {...('username')}/>
</div>
<div>
<label >密码</label>
<input type="text" name="password" {...('password')}/>
</div>
<div onClick={}>
提交
</div>
</div>
)
}
}
高阶组件:
import React,{Component } from 'react';
const formCreate = WrapComponent => class extends Component {
constructor(){
super();
={fields:{}}
}
onChange = key => e =>{
const { fields } = ;
fields[key] = ;
({
fields,
});
}
handleSubmit=()=>{
()
}
getField = fieldName =>{
return {
onChange:(fieldName)
}
}
render(){
const props = {
...,
handleSubmit:,
getField:,
}
return(<WrapComponent {...props}/>)
}
}
export default formCreate;
1.反向继承(也称控制反转):
去继承WrappedComponen; 本来是一种嵌套的关系,结果高阶组件返回的组件却继承了WrappedComponent,这看起来是一种反转的关系。
通过继承WrappedComponent,除了一些静态方法,包括生命周期,state,各种function,我们都可以得到。
父组件:
import React , { Component } from 'react';
export default class Usual extends Component {
constructor(){
super();
= {
usual : 'usal'
}
}
componentDidMount(){
('didMount')
}
render(){
return (
<div>
{}
</div>
)
}
}
高阶组件:
import React from 'react';
const iiHoc = WrapedComponent => class extends WrapedComponent {
componentDidMount(){
()
({
usual:1
})
setInterval(()=>{
({usual:+1})
}, 1000)
}
render(){
('hello world')
return ();
}
}
export default iiHoc;