如何替换“这个”在带有钩子的功能性React Native中?

问题描述

我正在尝试使用以下react-native-echarts-wrapper,但在我的项目中,我所有的组件都是使用钩子制成的。因此,当我有一个状态变量要更改其状态时,我想执行功能setoption(option),该选项包含状态值。

问题是在文档中使用setoption()引用了函数this.chart.setoption(option)。如果我尝试在没有this.的情况下放置,则会收到一条消息,其中chart是未定义的;如果仅使用函数,则会收到一条消息,指出setoption is not a function

有没有办法使用RN挂钩获得图表组件及其功能的引用?

这是我的代码

const [radarChartData,seTradarChartData] = React.useState([])
const option = { 
title: {
    show:false,text: 'Gráfico Radar'
},tooltip: {},legend: {
orient: 'horizontal',position:'bottom',left: 0,bottom:0,type:'scroll',pageButtonPosition:'end',data: chartColumnNameArray,},radar: {
    radius:'70%',name: {
        textStyle: {
            color: '#fff',backgroundColor: '#999',borderRadius: 3,padding: [3,5]
        }
    },indicator: chartValueArray.map((item,index)=>{
    return {name:chartColumnNameArray[index].toupperCase().substring(0,5).concat('.'),max:maxValue}
    })
},series: [{
    name: 'TEST',type: 'radar',data: radarChartData <------------------- //when this state changes I would setoptions and reload chart
}]
};

<View style={{display:  visibleChart==="radarchart"?"flex":"none",width:'100%',height:'60%'}} >                     
         <ECharts option={option} additionalCode={React.useEffect(()=>{this.chart.setoption(option)},[radarChartData])}/>                                                              
</View>

解决方法

您将不得不使用'useRef'钩子来访问图表,即使在提供的示例中,它们使用了对图表的引用并进行了更新。 我已经举了一个基本的示例来更改背景色,这将使您了解如何在图表上使用挂钩。只需设置参考并使用chart.current代替this.chart。

import React,{ Component } from 'react';
import { StyleSheet,View,Button } from 'react-native';
import { ECharts } from 'react-native-echarts-wrapper';

export default function App() {
  const chart = React.useRef(null);
  const option = {
    xAxis: {
      type: 'category',data: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],},yAxis: {
      type: 'value',series: [
      {
        data: [820,932,901,934,1290,1330,1320],type: 'line',],};

  return (
    <View style={styles.chartContainer}>
      <Button
        title="Update"
        onPress={() => {
          if (chart) {
            chart.current.setBackgroundColor('rgba(0,255,0.3)');
          }
        }}
      />
      <ECharts
        ref={chart}
        option={option}
        backgroundColor="rgba(93,169,81,0.4)"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  chartContainer: {
    flex: 1,});