本质是函数,将组件作为接收参数,返回一个新的组件。HOC本身不是React API,是一种基于React组合的特而形成的设计模式。
无论哪种方法,都是在HOC函数内定义新的组件,在新的组件内做一些公共的功能和事情
这是最常规的写法,原理等同于ES7装饰器、Python装饰器。函数传入的参数,除了原组件,还可以定义其他的参数,通过这些参数来区别每个实际组件。比如,公共的功能是获取数据。获取数据这件事情是相同的,但获取的内容不同。如何决定最后生成的组件获取各自指定的内容呢?通过函数传参。
// 示例用localstorage代替如网络请求等的异步操作
localStorage.setItem("comment","asuiklfhs");
localStorage.setItem("read","123");
class Comment extends React.Component {
render() {
return (
<div>
{this.props.data}
</div>
)
}
}
class Read extends React.Component {
render() {
return (
<div>
{this.props.data}
</div>
)
}
}
const HOCTest = (key) => {
return (WrappedComponent) => {
return class NewComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
data: ‘‘
};
}
componentDidMount() {
const data = localStorage.getItem(key);
this.setState({
data
});
}
render() {
console.log(this.myRef);
return (
<div ref={(e)=>{this.myRef = e;}}>
<WrappedComponent {...this.props} data={this.state.data} />
</div>
);
}
}
}
};
const CommentNew = HOCTest("comment")(Comment); // HOC生成新组件
const ReadNew = HOCTest("read")(Read);
class Root extends React.Component {
render() {
return (
<div className="App">
Hello World
<CommentNew/>
<ReadNew/>
</div>
);
}
}
在这里,React第三方的组件库通常使用 函数柯里化 的写法。对于使用者来说,改变了调用函数时的传参方式,更加容易理解。即:原本调用函数wrapper(Component, params1, params2) 柯里化后调用wrapper(params1,params2)(Component)
属性代理常见的作用:
顾名思义,就是将返回的组件继承了原组件。它允许生成的组件通过this获取原组件,意味着可以获取到state,props,生命周期钩子,以及render
localStorage.setItem("comment","asuiklfhs");
localStorage.setItem("read","123");
class Comment extends React.Component {
constructor(props){
super(props);
this.state = {id:"comment"}
}
componentDidMount() {
console.log("Comment DidMount");
}
render() {
return (
<div>
{this.props.data}
</div>
)
}
}
class Read extends React.Component {
constructor(props){
super(props);
this.state = {id:"read"}
}
render() {
return (
<div>
{this.props.data}
</div>
)
}
}
const HOCTest = (key) => {
return (WrappedComponent) => {
return class NewComponent extends WrappedComponent{
componentDidMount() {
console.log("HOC DidMount");
const data = localStorage.getItem(key);
this.setState({
...this.state,
data
});
}
render() {
return (
<WrappedComponent data={this.state.data}/>
);
}
}
}
};
const CommentNew = HOCTest("comment")(Comment);
const ReadNew = HOCTest("read")(Read);
class Root extends React.Component {
render() {
return (
<div className="App">
Hello World
<CommentNew/>
<ReadNew/>
</div>
);
}
}
作用:
原文:https://www.cnblogs.com/V587Chinese/p/11444842.html