如何将一个React功能组件绑定到另一个? (DevExtreme图表到PivotGrid)

时间:2019-06-30 15:19:53

标签: reactjs devextreme

我们更喜欢尽可能使用功能性的无状态React组件(尤其是现在使用React Hooks)。

但是,我无法弄清楚如何实现将DevExtreme PivotGrid绑定到图表的效果(这样人们可以进行组合操作)。

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

它们将Class组件与ref一起使用,然后在组合的Class组件挂载时使用:

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

我们宁愿不要那样走。有什么可以与新的React useRef()挂钩一起使用的巧妙技巧,还是通过向图表提供HTML文档ID以便我们可以在初始加载后的某个时间绑定这两个组件?

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

1 个答案:

答案 0 :(得分:1)

除了以钩子方式进行的简单更改外,我什么都没有想到,也就是将代码放在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