gpt4 book ai didi

javascript - 使用 recompose 映射从上下文中消耗的 Prop

转载 作者:行者123 更新时间:2023-11-29 17:42:40 38 4
gpt4 key购买 nike

我有一个功能组件,需要渲染 heightwidth Prop 。我们称它为 PureSizableDiv:

const PureSizableDiv = ({ height, width }) =>
<div style={{ height, width }}>I'm a div!</div>

我还有一个名为 Size 的 React 上下文:

import React from 'react';
import { compose, fromRenderProps } from 'recompose';

export const { SizeProvider, SizeConsumer } = React.createContext({
height: null,
width: null,
});

而不是像这样手动创建一个新的 HoC:

export const withSize = Component => (props) =>
<SizeConsumer>
{
({ height, width }) =>
<Component
height={height}
width={width}
{...props}
/>
}
</SizeConsumer>;

我想知道是否有使用 recompose 的更短更简洁的方法来执行此操作。我试过了

export const withSize = compose(
fromRenderProps(SizeConsumer, ({ height, width }) => ({ height, width })),
);

但出现错误 Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.您可能忘记从定义它的文件中导出您的组件,或者您可能混淆了默认导入和命名导入。

最佳答案

我已经连接了我的组件,但我没有正确使用 Context API。我修复了代码,它使用 recompose 中的 fromRenderProps 完美地工作。工作代码:

import React from 'react';
import { compose, fromRenderProps } from 'recompose';

const PureSizableDiv = ({ height, width }) =>
<div style={{ height, width }}>I am a div!</div>;

const SizeContext = React.createContext({
height: null,
width: null,
});

const withSize = compose(
fromRenderProps(SizeContext.Consumer, ({ height, width }) => ({ height, width })),
);

// Usage
const Wrapper = ({ children, height, width }) =>
<SizeContext.Provider
value={{
height: height,
width: width,
}}
>
{children}
</SizeContext.Provider>;

const SizedDiv = withSize(PureSizableDiv);

// Render components
<Wrapper>
<SizedDiv/>
</Wrapper>

关于javascript - 使用 recompose 映射从上下文中消耗的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083425/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com