【问题标题】:Using custom container with functional component使用带有功能组件的自定义容器
【发布时间】:2021-10-13 23:25:59
【问题描述】:

我已经定义了一个自定义容器:

const CombinedContainer = createContainer("selection", "voronoi");

const selectionStyle = {
  fill: "transparent",
  fillOpacity: 0.5,
  stroke: "red",
  strokeWidth: 1
}

type Props = {}

const ChartContainer = (props: Props) => (
  <CombinedContainer
    // @ts-ignore
    cursorDimension="x"
    selectionDimension="x"
    selectionStyle={selectionStyle}
    labels={({datum}) => `${datum.x}, ${datum.y.toFixed(2)} ${datum.volume}`}
  />
)

export default ChartContainer;

并像这样使用它:

<VictoryChart
  width={width}
  padding={padding}
  minDomain={{ y: 70 }}
  maxDomain={{ y: dataSet.maxDomain }}
  containerComponent={<ChartContainer />}
>
  ...
</VictoryChart>

但这不会渲染任何东西,除非我像普通函数一样使用它:

<VictoryChart
  width={width}
  padding={padding}
  minDomain={{ y: 70 }}
  maxDomain={{ y: dataSet.maxDomain }}
  containerComponent={ChartContainer({})}
>
  ...
</VictoryChart>

我之前定义了类似的功能组件并使用它们没有任何问题,但我看不出我在这里做错了什么。谁能帮帮我?

为什么&lt;ChartContainer /&gt; 不起作用,而ChartContainer() 起作用?

createContainer函数定义为:

export type ContainerType =
  | "brush"
  | "cursor"
  | "selection"
  | "voronoi"
  | "zoom";
export function createContainer<V, W>(
  c1: ContainerType,
  c2: ContainerType
): React.ComponentType<V & W>;

这是测试它的示例项目:

https://github.com/olcayertas/victory-functional-container-componenet

【问题讨论】:

  • createContainer 函数返回什么?
  • 它返回一个组件类型,我已经用定义更新了问题。
  • 你能设置最小的可重现示例吗?
  • @AlekseyL。我已经添加了项目链接。

标签: reactjs typescript react-functional-component victory-charts


【解决方案1】:

它不起作用,因为 ChartContainer 没有传递收到的道具(也没有 render the children)。

所以只需{...props} CombinedContainer

const ChartContainer = (props: Props) => (
  <CombinedContainer
    // @ts-ignore
    cursorDimension="x"
    selectionDimension="x"
    selectionStyle={selectionStyle}
    // @ts-ignore
    labels={({ datum }) =>
      `Date: ${datum.date}\nPrice: $${datum.close.toFixed(2)}\nVolume: ${
        datum.volume
      }`
    }
    {...props}
  />
);

Working example

【讨论】:

  • 非常感谢 Aleksey!
  • 这只是修复了渲染问题,但图表仍然无法正常工作:标签未显示且选择不起作用。非常有趣,我会在 Victory GitHub 上问这个。
  • 显然现在无法使用功能组件:github.com/FormidableLabs/victory/issues/1758
猜你喜欢
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 2021-08-12
  • 2018-06-09
  • 2011-04-03
相关资源
最近更新 更多