2

我有一个需要道具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.

4

2 回答 2

3

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

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>
于 2018-08-29T18:12:53.260 回答
1

您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

出现错误是因为您没有使用 compose 导出组件:

export const withSize = compose(
  fromRenderProps(SizeConsumer, ({ height, width }) => ({ height, width })),
)(Component);
// ^^
于 2018-08-29T18:00:02.880 回答