React Chart.js onClick用于自定义传说



我正在使用react-chartjs-2为我的应用程序创建销售图表。

对于此应用程序,我进行了一个传奇定制,可以使用以下方式生成它们:

// Chart component
<Line ref={ (chart) => chart ? this.insertLegends(chart) : null }
      data={this.state.chart} 
      options={this.state.options}  
/>
// Method which insert the html content
insertLegends(chart) {
   this.refs.chartLegendContainerGlobal.innerHTML = chart.chart_instance.generateLegend();
}

首先,这是正确的方法吗?我必须在组件内部创建一个内联条件,以防止图表为null。

第二,我如何以及在哪里可以为每个传说放置一个活动?

我对此感到非常迷失,有没有更好的方法来进行这个传奇定制?

如果您给裁判返回回调,那么您将无法获得null的值。这样的内联裁判会导致第一个渲染为null,然后第二个渲染将具有元素。

因此,您应该更改您的裁判:

applyRef(ref) {
    this.legend = ref;
}
render() {
    return (
        // Chart component
        <Line ref={this.applyRef}
              data={this.state.chart}
              options={this.state.options}
        />
    )
}

用于添加单击事件处理程序,如果由于某种原因无法添加onClick属性,则可以在insertLegends方法中设置它:

handleClick(e) {
    // Do something here...
}
insertLegends(chart) {
    this.refs.chartLegendContainerGlobal.innerHTML = chart.chart_instance.generateLegend();
    this.refs.chartLegendContainerGlobal.addEventListener('click', this.handleClick);
}

经过一些麻烦和研究后,我想出了如何添加传奇并控制其内部的单击。

// Inside my render method I added a simple ref to my component
<Line ref='chart' data={this.convertData(this.props.data)}  options={this.state.options} />
// Inside this method I'm able to get all the references that 
// I need to inject the html inside a container for the legends and 
// also to assign a click for each legend label
componentDidMount() {
   let legends = this.refs.chart.chart_instance.generateLegend();
   this.refs.chartLegendContainer.innerHTML = legends;
   $(this.refs.chartLegendContainer).find('.legend-item').on('click', (e) => {
      let index = $(e.currentTarget).index();
      this.refs.chart.chart_instance.data.datasets[index].hidden = !this.refs.chart.chart_instance.data.datasets[index].hidden;
      $(e.currentTarget).toggleClass('disable-legend');
      this.refs.chart.chart_instance.update();
   });
}

更新

@chase deanda的委托后,我根据他的考虑而改变了一点:

// Applying the callback function to the ref
<Line ref={this.applyRef} data={this.convertData(this.props.data)}  options={this.state.options} />
// Inside the method I call the method to insert the legends
applyRef(ref) {
   this.legend = ref;
   this.insertLegends();
}
// Generates the legend and added them to my container element
// Also give them the onClick event
insertLegends() {
   let legends = this.legend.chart_instance.generateLegend();
   this.refs.chartLegendContainer.innerHTML = legends;
   $(this.refs.chartLegendContainer).find('.legend-item').on('click', (e) => this.onClickLegend(e));
}
// During onClick I update the chart
onClickLegend(e) {
   let index = $(e.currentTarget).index();
   this.legend.chart_instance.data.datasets[index].hidden = !this.legend.chart_instance.data.datasets[index].hidden;
   $(e.currentTarget).toggleClass('disable-legend');
   this.legend.chart_instance.update();
}

最新更新