如何制作身份较高阶的组件,即仅呈现输入组件的较高阶组件?
说明:给定组件
const TestComponent = () => <div>TEST</div>
我希望以下内容等效:
export default TestComponent;
export default identityHOC(TestComponent);
我尝试过
const identityHOC = (Component) => (props) => Component(props);
const identityHOC = (Component) => (props) => () => Component(props);
const identityHOC = (Component) => (props) => <Component {...props} />;
const identityHOC = (Component) => (props) => () => <Component {...props} />;
和其他变体,但是它们不起作用。
答案 0 :(得分:2)
HOC基本上是只是一个功能,当提供组件时,它会返回另一个(或相同的,如果需要的话)
。尝试一下
import React from 'react';
const identityHOC = (WrappedComponent) => {
class HOC extends React.Component {
constructor(props){
super(props)
}
render() {
return <WrappedComponent {...this.props}/>;
}
}
return HOC;
};
如果要将其编写为功能组件,
import react from 'React'
const identityHOC = (WrappedComponent) => props =>
(<WrappedComponent {...props}/>)
您可能已经忘记了导入React。
答案 1 :(得分:1)
实施HOC(从Vinay Chandran的答案扩展)。
定义HOC功能。它应该返回带有签名(属性)的东西=>
import react from 'React'
const wrapWithHOC = (WrappedComponent) => props =>
(<WrappedComponent {...props}/>)
const BaseComponent = () => (
<div>TEST</div>
);
const WrappedComponent = wrapWithHOC(BaseComponent)
<App>
<WrappedComponent />
</App>
import react from 'React'
const wrapWithHOC = (WrappedComponent) => props =>
(<WrappedComponent externalProp="ExternalProp Example" {...props}/>)
const BaseComponent = ({ internalProp, externalProp}) => (
<div>
internal prop is: {internalProp}
external prop is: {externalProp || 'Not Wrapped'}
</div>
);
const WrappedComponent = wrapWithHOC(BaseComponent)
<App>
<WrappedComponent internalProp="This is a standard prop" />
</App>