Reactjs 简单高阶分量
我的目的是制作一个简单的高阶组件,其中我有一个可重用的节组件,我可以在其中定义一些css类和Reactjs 简单高阶分量,reactjs,react-props,react-functional-component,higher-order-components,Reactjs,React Props,React Functional Component,Higher Order Components,我的目的是制作一个简单的高阶组件,其中我有一个可重用的节组件,我可以在其中定义一些css类和标记: import React from 'react' function SectionWrapper(props) { return <section>{props.children}</section> } export default SectionWrapper 从“React”导入React 功能部分包装器(道具){ 返回{props.children} }
标记:
import React from 'react'
function SectionWrapper(props) {
return <section>{props.children}</section>
}
export default SectionWrapper
从“React”导入React
功能部分包装器(道具){
返回{props.children}
}
导出默认节包装器
现在,在我的父组件中,我可以像这样包装我的子部分组件:
<SectionWrapper>
<SectionTitle />
</SectionWrapper>
<SectionWrapper>
<List />
</SectionWrapper>
有没有更干净的方法来实现这一点?例如,如何将子组件作为道具传递?是的,您可以这样做-
const withSection = (Component) => (props) =>
<section><Component {...props}/></section>
const EnhancedSectionTitle = withSection(SectionTitle)
const with section=(组件)=>(道具)=>
const EnhancedSectionTitle=带节(SectionTitle)
然后像这样使用它
<EnhancedSectionTitle />
将
EnhancedSectionTitle
重命名为应用程序中有意义的名称您可以将节包装器转换为更高阶的组件,例如:
const withSection = Component => props => (
<section>
<Component {...props} />
</section>
);
constwithsection=Component=>props=>(
);
确保返回一个有效的react组件,该组件允许道具传递到被包装的底层组件
用法:
const ComponentWithSection = withSection(MyComponent);
...
<ComponentWithSection myProp={myAwesomeProp} />
const ComponentWithSection=withSection(MyComponent);
...
您可以将其转换为一个HOC,但对于这样一个简单的示例,它不会向包装中注入任何新的道具或行为,我不太明白包装是HOC的意义。