首页 > 解决方案 > 如何使用库提供的辅助函数?

问题描述

在此处输入图像描述

我正在使用 react-native-animated-charts 来渲染图表。但是,我很难读取可移动图表点的 x 和 y 值。文档提到 useChartData 帮助函数可以访问此信息。但是,我不确定如何使用(甚至不确定在哪里使用或初始化此功能)。

编辑:我添加了下面的代码

import React, {useEffect, useState, useRef} from 'react';
import {Text, Dimensions, View, TouchableHighlight, StyleSheet} from 'react-native';
import {
  ChartDot,
  ChartPath,
  ChartPathProvider,
  ChartYLabel,
  ChartXLabel,
  useChartData,
  monotoneCubicInterpolation,
} from '@rainbow-me/animated-charts';
import {runOnJS} from 'react-native-reanimated';
import Card2View from '..//Card2View/Card2View';


import styles from './styles';

export const {width: SIZE, height} = Dimensions.get('window');
const TABLE_ITEM_OFFSET = 10;
const TABLE_ITEM_MARGIN = TABLE_ITEM_OFFSET * 2;
const SCREEN_WIDTH = SIZE < height ? SIZE : height;

export const data = [
  {x: 1453075200, y: 1.47},
  {x: 1453161600, y: 1.37},
  {x: 1453248000, y: 1.53},
  {x: 1453334400, y: 1.54},
  {x: 1453420800, y: 1.52},
  {x: 1453507200, y: 2.03},
  {x: 1453593600, y: 2.1},
  {x: 1453680000, y: 2.5},
  {x: 1453766400, y: 2.3},
  {x: 1453852800, y: 2.42},
  {x: 1453939200, y: 2.55},
  {x: 1454025600, y: 2.41},
  {x: 1454112000, y: 2.43},
  {x: 1454198400, y: 2.2},
];



const points = monotoneCubicInterpolation({data, range: 40});
const LineChartView1 = ({priceData}) => {

  const [activeChart, setActiveChart] = useState(0)
  const lineChartTables = ['1D', '1W', '1M', '3M', '1Y', 'ALL'];

  const output = useChartData()

  console.log(output);

  const getX = value => {
    'worklet';
    // console.log(runOnJS(useChartData("state")));
    if (value === '') {
      return '';
    }
    return `$ ${value.toLocaleString('en-US', {
      currency: 'USD',
    })}`;
  };
  
  const getY = value => {
    'worklet';
    // console.log(runOnJS(useChartData("state")));
    if (value === '') {
      return '';
    }
    const date = new Date(Number(value * 1000));
    const s = date.getSeconds();
    const m = date.getMinutes();
    const h = date.getHours();
    const d = date.getDate();
    const n = date.getMonth();
    const y = date.getFullYear();
    return `${y}-${n}-${d} ${h}:${m}:${s}`;
  };

 

  renderTable = (item, index) => (
    <TouchableHighlight
        onPress={() => setActiveChart(index)}
        underlayColor="rgba(73,182,77,1,0.9)"
        key={index}
        style={
          activeChart == index
            ? {
                justifyContent: 'center',
                backgroundColor: '#617180',
                borderRadius: 5,
                flex: 1,
                alignItems: 'center',
                margin: TABLE_ITEM_OFFSET,
                width:
                  (SCREEN_WIDTH - TABLE_ITEM_MARGIN) / lineChartTables.length -
                  TABLE_ITEM_OFFSET,
                height:
                  (SCREEN_WIDTH - TABLE_ITEM_MARGIN) / lineChartTables.length -
                  TABLE_ITEM_OFFSET,
                maxWidth: 50,
                maxHeight: 50
              }
            : {
                justifyContent: 'center',
                backgroundColor: 'white',
                borderRadius: 5,
                flex: 1,
                alignItems: 'center',
                margin: TABLE_ITEM_OFFSET,
                width:
                  (SCREEN_WIDTH - TABLE_ITEM_MARGIN) / lineChartTables.length -
                  TABLE_ITEM_OFFSET,
                height:
                  (SCREEN_WIDTH - TABLE_ITEM_MARGIN) / lineChartTables.length -
                  TABLE_ITEM_OFFSET,
                maxWidth: 50,
                maxHeight: 50
              }
        }
      >
        <Text style={activeChart == index ? chart.activeChartTxt : chart.chartTxt}>
          {item}
        </Text>
      </TouchableHighlight>
    );
      
  return(
    
    <View>
      <Card2View item={{title:priceData.symbol, text:priceData.lastUpdatedPrice, money:`Rs. ${priceData.lastUpdatedPrice}`, procent:`${(priceData.percentageChange).toFixed(2)}`}} />
    <View
    style={{backgroundColor: 'white'}}>
      
    <ChartPathProvider
      data={{
        points,
        smoothingStrategy: 'bezier',
      }}
      >
        
      <ChartPath height={SIZE / 2} stroke="black" strokeWidth="2" selectedOpacity="0.3" width={SIZE} />
      <ChartDot
        style={{
          backgroundColor: 'black',
        }}
        size={15}
      />
      {/* <ChartYLabel format={getX} style={{backgroundColor: 'white', color: 'black'}}/>
      <ChartXLabel format={getY} style={{backgroundColor: 'white', color: 'black'}}/> */}
    </ChartPathProvider>


    <View style={{ flexDirection: 'row', justifyContent: 'space-around', flex: 1 }}>
        {lineChartTables.map((data, index) => renderTable(data, index))}
    </View>
  </View>
  </View>
  )
  
}

export default LineChartView1;

const chart = StyleSheet.create({
  chartTxt: {
    fontSize: 14,
    color: 'black'
  },
  activeChartTxt: {
    fontSize: 14,
    color: 'white',
    fontWeight: 'bold'
  }
});

标签: androidreactjsreact-nativereact-hooks

解决方案


你需要调用里面的钩子ChartPathProvider。例子:

const ChildComponent = () => {
    const values = useChartData();
    return <Text>{values.greatestX}</Text>
}
const ParentComponent = ({ points }) => (
   <ChartPathProvider 
       data={{
           points,
           smoothingStrategy: 'bezier',
       }}
   >
       {/* other chart components */}
       <ChildComponent />
   </ChartPathProvider>
)

在您的示例中,您在定义提供者之前调用了钩子(即在 return 语句之前)。


推荐阅读