好的,您对如何使用 HOC 有点不了解。这是一个简单的例子,我将解释。
function giveColor( WrappedComponent, color ) {
return class extends Component {
componentDidMount() {
this.wrapperEl.children[ 0 ].style.color = color;
}
render() {
console.log(this.props)
return (
<div ref={ ( el ) => this.wrapperEl = el }>
<WrappedComponent { ...this.props } />
</div>
);
}
}
}
const PrintName = ({ name }) => (
<div>{ name }</div>
);
const PrintRedName = giveColor( PrintName, "#ff0000" );
您将使用 PrintRedName 如下:<PrintRedName name="Bubowski" />
由于从 HOC 返回的类的 render 方法中的调用,您提供的name
属性将传递给包装的组件。{ ...props }
<WrappedComponent />
HOC 用作另一个组件上的函数,如下所示:const PrintRedName = giveColor( PrintName, "#ff0000" );
我用 PrintName 组件作为第一个参数调用 giveColor HOC,第二个参数是我想要设置的颜色。
在 HOC 中,我将 WrappedComponent 包装在一个 div 中,我给出了一个ref
用于更改ref
.
这是一个人为的例子,但我希望它可以帮助你理解:)
一些很好的HOC 示例connect()
来自react-redux和react-routerwithRouter()
编辑:针对您的最新问题:
我将您链接到的代码编辑为以下内容以使其正常工作,请阅读代码中的注释。
const wrapComponent = (WrappedComponent) =>
class extends Component {
render() {
return (
<div>
I wrapped:
<WrappedComponent {...this.props} />
</div>
)
}
}
const ComponentA = ({name}) => <div><b>{name}</b></div>;
const ComponentB = wrapComponent(ComponentA);
// You had...
/*
No need to wrap a component wrapping itself, but the problem here is,
You're nesting evalutions by doing { ...code } inside
() => ( single evaluation )
const App = () => (
{ wrapComponent(ComponentB) }
)
*/
const App = () => (
<ComponentB name="My name" />
)
render(<App />, document.getElementById('root'));