用react-native-chart-kit图表填充父容器(React Native,Expo)

时间:2019-08-25 22:17:12

标签: javascript reactjs react-native expo react-native-chart-kit

我正在React Native Expo应用中使用react-native-chart-kit来渲染图表。文档中提供的示例可以正常工作

问题::在我的应用中,需要使用图表来填充父容器,但是看起来图表必须具有height道具作为固定值。

<LineChart
    height={221}
    ...
/>

尝试将height的值设置为100%或删除定义将导致与NaN相关的错误

  

不变违反:[.....,“ y1”:“ <>”,“ x2”:“ 375”,“ y2”:“ <>”}]不能用作本机方法参数

是否有解决此问题的方法?谢谢!

基于文档的工作示例

export default class Chart extends Component {

    render() {
        const data = {
            datasets: [{
                data: [
                    Math.random() * 100,
                    Math.random() * 100,
                    Math.random() * 100,
                    Math.random() * 100,
                    Math.random() * 100,
                    Math.random() * 100
                ]
            }]
        }

        return (
            <LineChart 
                data={data}
                width={Dimensions.get('window').width}
                height={221}
                yAxisLabel={'$'}
                chartConfig={{
                    backgroundColor: '#e26a00',
                    backgroundGradientFrom: '#fb8c00',
                    backgroundGradientTo: '#ffa726',
                    decimalPlaces: 2, // optional, defaults to 2dp
                    color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                    style: {
                        borderRadius: 16
                    }
                }}
                bezier
                style={{
                    marginVertical: 8,
                    borderRadius: 16
                }}
            />
        )
    }

}                   

@hong开发

react-native-chart-kit组件<LineChart />可以是高度可变的另一个组件的子组件。因此<LineChart />不必具有Dimensions.get('window').height;给定的高度。例如,

render() {
    <View>
        <Header />
        { this.props.foo ? this.renderFoo() : null }
        <View>
            <LineChart 
                ...
            />
        </View>
    </View>
}

1 个答案:

答案 0 :(得分:1)

height的类型为number。因此,不允许string values。如果要替换您要尝试执行的操作,则可以使用它。

const screenheight = Dimensions.get('window').height;
<LineChart
    height={screenheight}
    ...
/>

正如您通过参考this document,所看到的,不设置高度就无法看到图表。由于宽度和高度是由设置值设置的,因此必须无条件记下该值。