【问题标题】:How to bind one React Functional Component to another? (DevExtreme Chart to PivotGrid)如何将一个 React 功能组件绑定到另一个? (DevExtreme Chart 到 PivotGrid)
【发布时间】:2019-06-30 15:19:53
【问题描述】:

我们更喜欢尽可能使用函数式无状态反应组件(尤其是现在使用 React Hooks)。

但是,我不知道如何实现将 DevExtreme PivotGrid 绑定到图表的效果(以便获得组合操作)。

从他们的例子中可以看出:https://js.devexpress.com/Demos/WidgetsGallery/Demo/PivotGrid/ChartIntegration/React/MaterialTealDark/

他们使用带有 ref 的 Class 组件,然后在组合的 Class 组件挂载时执行:

  componentDidMount() {
    this._pivotGrid.bindChart(this._chart, {
      dataFieldsDisplayMode: 'splitPanes',
      alternateDataFields: false
    });
  }

我们宁愿不走那条路。是否有一些巧妙的技巧可以与新的 React useRef() hook 一起使用,或者通过将 HTML doc id 提供给图表,以便我们可以在初始加载后的某个时间绑定两个组件?

我们不是这里的纯粹主义者,所以即使是稍微丑陋的解决方案也可以。

【问题讨论】:

  • 我觉得你已经知道要走哪条路了。为什么不使用 useRef() 挂钩并尝试一下?
  • 我尝试了一些关于 useRef() 的想法,但我不得不承认,我一定没有完全掌握如何将它用于这种用法

标签: reactjs devextreme


【解决方案1】:

除了用 Hooks 方式做一个简单的改变之外,我想不出任何办法,也就是将代码放在 useEffect() 钩子中并使用 useRef() 绑定参考:

// import useEffect and useRef hook from 'react', 
import React, { useEffect, useRef() } from 'react'    

function App() {
  // initialize the ref variables with null as the initial value,
  const pivotGrid = useRef(null);
  const chart = useRef(null);

  // useEffect runs after the layout paint...
  useEffect(() => {
      // do the binding on the references,
      pivotGrid.current.bindChart(chart.current, {
         dataFieldsDisplayMode: 'splitPanes',
         alternateDataFields: false
      });
  }
  ,
  // we pass an empty array to only run once after the component mount,
  [])

  // pass the refs variables to the components.
  return (
  <React.Fragment>
    <Chart ref={chart}>
      <Size height={320} />
      <Tooltip enabled={true} customizeTooltip={customizeTooltip} />
      <CommonSeriesSettings type={'bar'} />
      <AdaptiveLayout width={450} />
    </Chart>

    <PivotGrid
      id={'pivotgrid'}
      dataSource={dataSource}
      allowSortingBySummary={true}
      allowFiltering={true}
      showBorders={true}
      showColumnTotals={false}
      showColumnGrandTotals={false}
      showRowTotals={false}
      showRowGrandTotals={false}
      ref={pivotGrid}
    >
      <FieldChooser enabled={true} height={400} />
    </PivotGrid>
  </React.Fragment>
);
}

我不能 100% 确定您是否需要传递 ref.current 或只是传递 ref 本身。两种方法都可以试试!

编辑

Re:使用来自 React 文档的 useRef():

请记住,useRef 不会在其内容更改时通知您。 改变 .current 属性不会导致重新渲染。如果你想 在 React 将 ref 附加或分离到 DOM 节点时运行一些代码, 您可能想改用callback ref

【讨论】:

  • useEffect(() => { _pivotGrid.current.instance.bindChart(_chart.current.instance, { ...
  • 这样解决了吗?告诉我这个答案是否有用,我会更新它。
  • 整天开会。希望明天报告。
  • @P Fuster 当我将其更改为 current.instance 时。是的,它奏效了。但是你可能想看看这两篇关于这种方法的注意事项的文章(不涉及我的用例):(1)medium.com/@teh_builder/…(2)medium.com/better-programming/…
猜你喜欢
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多