我有一个需要道具height
并被width
渲染的功能组件。让我们称之为PureSizableDiv
:
const PureSizableDiv = ({ height, width }) =>
<div style={{ height, width }}>I'm a div!</div>
我还有一个名为的 React 上下文Size
:
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. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.