Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Higher-order Components 高阶组件 #13

Open
ybning opened this issue May 12, 2017 · 0 comments
Open

Higher-order Components 高阶组件 #13

ybning opened this issue May 12, 2017 · 0 comments
Labels

Comments

@ybning
Copy link
Owner

ybning commented May 12, 2017

Higher-order Components 高阶组件

import { Component } from "React" ;

export const Enhance = (ComposedComponent) => class extends Component {
    constructor() {
        this.state = { data: null };
    }
    componentDidMount() {
        this.setState({ data: 'Hello' });
    }
    render() {
        return <ComposedComponent {...this.props} data={this.state.data} />;
    }
};

Enhance 是一个方法,当传入一个 Component(ComposedComponent) 的时候,它将自动为该 Component 进行扩展并返回新的类定义。上例中,就返回了一个扩展的 Component 类,为构造函数中添加了 state,也在 React 生命周期函数 componentDidMount中添加了处理逻辑,而 render 方法则使用了传入的参数,完成了渲染。

新的业务逻辑由 Enhance 提供(通过返回新的 Component),传入的 ComposedComponent 就像一个回调函数。看看怎么使用:

import  { Component }  from "React";
import { Enhance } from "./Enhance";

class MyComponent = class extends Component {
      render() {
          if (!this.props.data) return <div>Waiting...</div>;
          return <div>{this.data}</div>;
      }
}

export default Enhance(MyComponent); // Enhanced component`

MyComponent 就是一个高阶组件(类似于高阶函数-回调函数),负责对特定的数据进行渲染。MyComponent 仅仅知道别人会把数据通过 this.prop.data 传进来,其他就都不关心了。可以看到,和 Mixins 的扩展方式相比,MyComponent 的工作要轻松很多。

原文:http://www.jianshu.com/p/4780d82e874a

This was referenced May 27, 2017
@ybning ybning added the react label May 27, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant