Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 简单高阶分量_Reactjs_React Props_React Functional Component_Higher Order Components - Fatal编程技术网

Reactjs 简单高阶分量

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} }

我的目的是制作一个简单的高阶组件,其中我有一个可重用的节组件,我可以在其中定义一些css类和
标记:

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的意义。