1.4 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			1.4 KiB
		
	
	
	
	
	
	
	
title, localeTitle
| title | localeTitle | 
|---|---|
| Higher-Order Components | 高阶组件 | 
高阶组件
在React中, 高阶组件 (HOC)是一个获取组件并返回新组件的函数。程序员使用HOC来实现组件逻辑重用 。
如果您使用过Redux的connect ,那么您已经使用过高阶组件。
核心思想是:
const EnhancedComponent = enhance(WrappedComponent); 
哪里:
- enhance是高阶分量;
- WrappedComponent是您要增强的组件;和
- EnhancedComponent是创建的新组件。
这可能是enhance HOC的主体:
function enhance(WrappedComponent) { 
  return class extends React.Component { 
    render() { 
      const extraProp = 'This is an injected prop!'; 
      return ( 
        <div className="Wrapper"> 
          <WrappedComponent 
            {...this.props} 
            extraProp={extraProp} 
          /> 
        </div> 
      ); 
    } 
  } 
 } 
在这种情况下, enhance返回一个扩展React.Component的匿名类 。这个新组件做了三件简单的事情:
- 在div元素中渲染WrappedComponent;
- 将自己的道具传递给WrappedComponent;和
- 向WrappedComponent注入额外的prop。
HOC只是一种利用React组成性质的力量的模式。 他们为组件添加功能 。你可以用它们做更多的事情!