如何使用react-native-animated-charts的useChartData辅助函数获取图表点坐标
问题原因
useChartData是用于消费<ChartPathProvider>提供的图表上下文状态的hook,必须在<ChartPathProvider>包裹的后代组件内部调用,你当前把它直接放在了LineChartView1的根作用域,此时还没有进入Provider的上下文范围,因此永远拿不到点位的坐标数据。
解决方案
方案1:直接使用内置标签(快速实现)
你代码中已经注释掉了ChartYLabel和ChartXLabel组件,这两个组件内部已经封装了useChartData的调用逻辑,直接解除注释即可在拖拽点位时显示实时坐标:
<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>
方案2:自定义组件获取数据(灵活扩展)
如果你需要自己拿到坐标值做额外逻辑处理,就抽离一个单独的子组件,在子组件内部调用useChartData:
- 首先定义子组件:
import { useEffect } from 'react'; import { View, Text } from 'react-native'; import { useChartData } from '@rainbow-me/animated-charts'; const ChartActivePoint = () => { // 在Provider后代组件中调用hook,即可拿到实时数据 const { currentX, currentY, state } = useChartData(); // 监听坐标变化 useEffect(() => { // state.isActive表示用户正在拖拽点位 if (state.isActive) { // 读取.value属性拿到具体坐标值 console.log('当前x坐标(时间戳):', currentX.value); console.log('当前y坐标(数值):', currentY.value); } }, [currentX.value, currentY.value, state.isActive]); // 自定义渲染坐标信息 return ( <View style={{ paddingHorizontal: 16, paddingVertical: 8 }}> <Text>当前价格:{currentY.value ? `$${currentY.value.toFixed(2)}` : '--'}</Text> <Text>对应时间:{currentX.value ? new Date(currentX.value * 1000).toLocaleString() : '--'}</Text> </View> ) }
- 把自定义组件放到
<ChartPathProvider>内部即可:
<ChartPathProvider data={{ points, smoothingStrategy: 'bezier', }} > <ChartPath height={SIZE / 2} stroke="black" strokeWidth="2" selectedOpacity="0.3" width={SIZE} /> <ChartDot style={{ backgroundColor: 'black', }} size={15} /> {/* 加入自定义组件 */} <ChartActivePoint /> </ChartPathProvider>
注意事项
useChartData返回的currentX、currentY是React Native Reanimated的共享值,在普通JS逻辑中需要读取.value属性拿到原生值,在worklet函数中可以直接使用。- 不要在
<ChartPathProvider>外部调用useChartData,否则无法拿到上下文数据。
内容的提问来源于stack exchange,提问作者Bigyan Karki
相关产品推荐
相关产品推荐

