浅谈React高阶组件(2)

const BaseActivity = (WrappedComponent, title) => { return class extends Component { render() { return ( <section> <div>{title}</div> <WrappedComponent /> </section> ) } } }

在Example中这样export

export default BaseActivity(Example, '这是高阶组件的参数');

我们看下输出的react dom

浅谈React高阶组件


可以看到参数已经传递进去了。

当然还可以这样用(柯里化)

const BaseActivity (title) => (WrappedComponent) => { return class extends Component { render() { return ( <section> <div>{title}</div> <WrappedComponent /> </section> ) } } }

在Example中这样export

export default BaseActivity('这是高阶组件的参数')(Example);

这种用法在ant-design的表单以及redux的connect中我们都可以看到

// ant const WrappedDemo = Form.create()(Demo) // redux export default connect(mapStateToProps, mapDispatchToProps)(Counter)

高阶组件还可以扩展原组件的props属性,如下所示:

const BaseActivity (title) => (WrappedComponent) => { return class extends Component { render() { const newProps = { id: Math.random().toString(8) } return ( <section> <div>{title}</div> <WrappedComponent {...this.props} {...newProps}/> </section> ) } } }

看下输出的react dom

浅谈React高阶组件


高阶组件的缺点

高阶组件也有一系列的缺点,首先是被包裹组件的静态方法会消失,这其实也是很好理解的,我们将组件当做参数传入函数中,返回的已经不是原来的组件,而是一个新的组件,原来的静态方法自然就不存在了。如果需要保留,我们可以手动将原组件的方法拷贝给新的组件,或者使用hoist-non-react-statics之类的库来进行拷贝。

结语

高阶函数对于初学者来说可能不太好理解,但当你深入其中,了解其中的原理之后,我们可以使用高阶函数来完成很多的工作。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxddw.html