定义:它接受任何输入(多数时候是一个组件)并返回一个组件作为输出。返回的组件是输入组件的增强版本,并且可以在 JSX 中使用。
创建一个简单的 HOC,它将一个组件作为输入并返回一个组件。
//一般用“with”前缀来命名 HOC
function withFoo(Component) {
return function(props) {
return <Component { ...props } />;
}
}
es6的写法
const withFoo = (Component) => (props) =>
<Component { ...props } />
使用场景:条件渲染
const Button = ({ onClick, className = '', children }) =>
<button
onClick={onClick}
className={className}
type="button"
>
{children}
</button>
const Loading = () =>
<div>Loading ...</div>
//定义hoc
const withLoading = (Component) => ({ isLoading, ...rest }) =>
isLoading
? <Loading />
: <Component { ...rest } />
//实例化一个hoc
const ButtonWithLoading = withLoading(Button);
//使用hoc
<ButtonWithLoading
isLoading={isLoading}
onClick={() => this.fetchSearchTopStories(searchKey, page + 1)}>
More
</ButtonWithLoading>