繁体   English   中英

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

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

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

问题是在文档中使用this.chart.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,
  },
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM