Javascript 反应合成函数与高阶函数的使用
我有一个JSX文件MyComponent.JSX,定义如下Javascript 反应合成函数与高阶函数的使用,javascript,reactjs,react-hooks,jsx,higher-order-functions,Javascript,Reactjs,React Hooks,Jsx,Higher Order Functions,我有一个JSX文件MyComponent.JSX,定义如下 import compose from 'compose-function' const MyComponent = () => { //some hooks like useState, useEffect here // finally returns some JSX return ( <> </> ) } function MyCo
import compose from 'compose-function'
const MyComponent = () => {
//some hooks like useState, useEffect here
// finally returns some JSX
return (
<>
</>
)
}
function MyComponentData(props) {
let StyledMyComponent = compose(
withStyle(style),
withTranslation('translation'),
withMyApi()
)(MyComponent);
return (
<MyContextProvider>
<StyledMyComponent />
</MyContextProvider>
);
}
export default MyComponentData;
从“合成函数”导入合成
常量MyComponent=()=>{
//这里有一些钩子,比如useState、useffect
//最后返回一些JSX
返回(
)
}
函数MyComponentData(道具){
让StyledMyComponent=compose(
用风格(风格),
用translation(“translation”),
withMyApi()
)(MyComponent);
返回(
);
}
导出默认MyComponentData;
现在“withMyApi”如下所示(在单独的Api.jsx文件中定义)
使用MyAPI()导出函数{
//额外函数包装。组成多个HOC是否需要此包装?
返回函数(WrappedComponent){
类myapirs扩展了React.Component{
建造师(道具){
超级(道具);
this.api={
数据源:数据源
}
}
render(){
const{title,content}=this.props;
返回(
);
}
}
返回myapirls;
}
}
下面是我的问题
let StyledMyComponent = withStyle(style)(withTranslation('translation')(withMyApi()(MyComponent)));
在MyAPI内部,我看到了一个额外的函数包装器。需要这样做吗
组成多个HOC?我的意思是整个语法相当混乱。
虽然我了解HOCs,但我只是想了解语法
在他的情况下使用它,特别是在如何使用它的上下文中
MyComponent.jsx
外部函数包装器用于在包装组件时配置。配置是静态的,不是通过标准React渲染过程从道具中获得的。这也是一种标准的函数式编程实践,称为currying。您可以通过传递第一组参数来调用函数,然后获得另一个函数,该函数也可以接受参数,依此类推。只有在调用最后一个返回的函数时,函数才会返回其结果
您可以在代码中看到两个示例:
-在渲染组件时传递要使用的样式使用样式(样式)
-在渲染组件时传递要使用的翻译withTranslation(“translation”)
let StyledMyComponent = withStyle(style)(withTranslation('translation')(withMyApi()(MyComponent)));
使用MyAPI()调用后,返回一个函数,该函数使用MyComponent
调用,这就是WrappedComponent
你可以在这里找到更多关于咖喱和写作的信息
您的代码有问题。使用MyComponentData
时,在每个渲染上重新创建StyledMyComponent
:
function MyComponentData(props) {
let StyledMyComponent = compose(
withStyle(style),
withTranslation('translation'),
withMyApi()
)(MyComponent);
return (
<MyContextProvider>
<StyledMyComponent />
</MyContextProvider>
);
}
let StyledMyComponent = withStyle(style)(withTranslation('translation')(withMyApi()(MyComponent)));
function MyComponentData(props) {
let StyledMyComponent = compose(
withStyle(style),
withTranslation('translation'),
withMyApi()
)(MyComponent);
return (
<MyContextProvider>
<StyledMyComponent />
</MyContextProvider>
);
}
const StyledMyComponent = compose(
withStyle(style),
withTranslation('translation'),
withMyApi()
)(MyComponent);
function MyComponentData(props) {
return (
<MyContextProvider>
<StyledMyComponent />
</MyContextProvider>
);
}