本文为 Marno 翻译,转载必须保留出处!
公众号【 Marno 】,关注后回复 RN 加入交流群
React Native 优秀开源项目大全:http://www.marno.cn
一、前言
在移动应用中制作折线图表是一件具有挑战性的事。本文将会教你如何只用 Component 和 StyleSheet 在 React Native 中制作一个折线图。
我们参考的是 《 Let’s drawing charts in React-Native without any library 》(需翻Q), 他介绍了如何在不引入三方库的情况下,在 React Native 中绘制柱状图和条形图。虽然在 react-native-chart这个库中已经有折线图了, 然而,今天我们要来定制我们自己的。
二、开始动手
首先,我们必须先绘制背景,为了显示水平轴,第一步要先绘制一些数字和直线。代码如下:
import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default function LevelSeparator({ label, height }) {
return (
{label.toFixed(0)}
);
}
LevelSeparator.propTypes = {
label: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired
};
export const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
label: {
textAlign: 'right',
width: 20
},
separatorRow: {
width: 250,
height: 1,
borderWidth: 0.5,
borderColor: 'rgba(0,0,0,0.3)',
marginHorizontal: 5
}
});
我们添加了一个 height 属性,因为我们会在下一步用到它。
然后使用上面封装好的直线组件,得到下图 1。代码如下:
export default class lineChartExample extends Component {
render() {
return (
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
height: 100
}
});
图 1 ▲
三、绘制背景
重复使用 ,完成折线图背景水平轴的绘制,为了以后方便调用,我们将这个过程封装起来。
import React from 'react';
import { View, StyleSheet } from 'react-native';
import LevelSeparator from './LevelSeparator';