说到高阶组件其实小伙伴你并不陌生,只是名字高大上,没啥东西说白了你自己工作中用到了很多只是没有注意到而已。好,现在我们去了解下。。。。
话不多说直接上个小栗子:
class Parents extends Component { constructor(props) { super(props); this.state = { parentsSourse: '我是父组件数据' } } render() { <> <Children /> 这是父组件,相当于我们的外层组件 </> } }
class Children extends Component { render() { <> 这是子组件,我们展示组件 </> } }
那么问题来了,我们假如我们想让父组件包含的组件都具有一个属性值,这个值是 newType: true, 此时我们可以直接向下级 Childlren 传递,那么我们也可以封装下父组件导出个高阶组件,那么这个方法可以这么写:
const Hoc_component = (HocCompoent) => { return class NewComponent extends React.Component{ constructor(props){ super(props); this.state={} } render() { const props = { newType: true } return <HocCompoent {...this.props} {...props}/> } } } // 此时所有的组件只要使用 Hoc_component(Children); // 此时的子组件就具有了这个方法包装的 newType属性,我们可以去打印看下。
好的,现在那你是不是能明白高阶组件的用法,其实就是封装个函数将传入的组件添加上数据,直接导出即可,我们常用的react-redux 中的 connect(Children) 一个道理,封装完将数据导入到组件当中,组件相应的具有数据,以及具有了dispatch方法,就是这么个封装。
感谢您的支持,希望您能点赞~~~