如何用 Hooks 替换函数式 React Native 中的 'this.'?

How to replace the 'this.' in the functional React Native with Hooks?

我正在尝试使用以下 react-native-echarts-wrapper 但在我的项目中,我的所有组件都是使用挂钩制作的。因此,当我有一个改变其状态的状态变量时,我想执行函数 setOption(option),其中选项包含状态值。

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

那么有没有办法使用RN Hooks获取图表组件及其功能的引用?

这是我的代码:

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' 挂钩才能访问图表,即使在提供的示例中,它们也使用图表的引用并更新它。 我已经做了一个更改背景颜色的基本示例,这将使您了解如何在图表中使用挂钩。只需设置 ref 并使用 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,0.3)');
          }
        }}
      />
      <ECharts
        ref={chart}
        option={option}
        backgroundColor="rgba(93, 169, 81, 0.4)"
      />
    </View>
  );
}

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