Элементы не отображаются в React Native

Текущий вывод: введите здесь описание изображения

Ожидаемый результат: введите здесь описание изображения Текущая реализация кода:

import React from 'react'
import { LineChart, XAxis, YAxis } from 'react-native-svg-charts'
import { View, Text } from 'react-native'
import { Line, Circle, G, Rect, } from 'react-native-svg'
export default class Chart extends React.PureComponent {
    handleFill = (value) => {
        if (value>100){
            return "rgba(190, 30, 45, 0.5)"
        }
        else if (value>80 && value<=100){
            return "yellow"
        }
        else{
            return "#CCE6D0"
        }
    }

    render() {

        const data = [
            ...
          ];

        const values = data.map(a => a.value);
        const days = data.map(a => a.day);
        const axesSvg = { fontSize: 10, fill: 'grey' };
        const verticalContentInset = { top: 10, bottom: 10 }
        const xAxisHeight = 30
        
        const Decorator = ({x, y, data}) => {
            return values.map((value, index) => (
            <View>
                <View style={{marginBottom:50}}>
                <Rect 
                    x={x(index)-1.75} 
                    y={y(value+8)} 
                    width="4" 
                    height="40" 
                    fill={this.handleFill(value)} 
                />
                </View>
                <Circle
                    key={index}
                    cx={x(index)}
                    cy={y(value)}
                    r={2}
                    stroke={'#639123'}
                    fill={'#606060'}
                    
                />
            </View>
            ));
          };
        return (
            <View>
                <Text style={{fontSize:10}}>BPM</Text>
                <View style={{ height: 200,  flexDirection: 'row' }}>
                    <YAxis
                        ...  
                    />
                    <View style={{ flex: 1, marginLeft: 10 }}>
                        <LineChart
                            ...
                        >
                            <Decorator />
                           
                        </LineChart>
                        <XAxis
                            ....
                        />
                    </View>
                </View>
            </View>
        )
    }

}

Я использую библиотеку react-native-svg-charts для отображения линейной диаграммы с пользовательскими обработчиками. Как видно из кода, обработчик состоит из круга и прямоугольника, которые просто не отображаются. Может ли это быть проблемой версии библиотеки? Я обновил и react-native-svg, и react-native-svg-charts до последней версии. Что мне не хватает? Любые идеи?


person Blake    schedule 24.09.2020    source источник


Ответы (1)


У меня получилось так:

import React from 'react';
import {LineChart, XAxis, YAxis} from 'react-native-svg-charts';
import {View, Text} from 'react-native';
import {Svg, Line, Circle, G, Rect} from 'react-native-svg';

export default class CustomLineChartOne extends React.PureComponent {
  handleFill = (value) => {
    if (value > 100) {
      return 'rgba(190, 30, 45, 0.5)';
    } else if (value > 80 && value <= 100) {
      return 'yellow';
    } else {
      return '#CCE6D0';
    }
  };

  render() {
    const xAxisLabels = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24];

    const Decorator = ({x, y, data}) => {
      return data.map((value, index) => (
        <View>
          <Rect
            x={x(index) - 1.75}
            y={y(value + 8)}
            width="4"
            height="40"
            rx="2"
            fill={this.handleFill(value)}
          />
          <Circle
            key={index}
            cx={x(index)}
            cy={y(value)}
            r={2}
            stroke={'#639123'}
            fill={'#606060'}
          />
        </View>
      ));
    };

    return (
      <View
        style={{
          height: 200,
          flexDirection: 'row',
          padding: 20,
        }}>
        <YAxis
          data={data}
          contentInset={{top: 20, bottom: 20}}
          svg={{
            fill: 'black',
            fontSize: 10,
          }}
        />
        <View style={{flex: 1}}>
          <LineChart
            style={{flex: 1}}
            data={data}
            svg={{stroke: 'rgb(134, 65, 244)'}}
            contentInset={{top: 10, bottom: 10, left: 10, right: 10}}>
            <Decorator />
          </LineChart>
          <XAxis
            style={{marginHorizontal: -10}}
            data={data}
            formatLabel={(value, index) => xAxisLabels[index]}
            contentInset={{left: 10, right: 10}}
            svg={{fontSize: 10, fill: 'black'}}
          />
        </View>
      </View>
    );
  }
}

Здесь важно обратить внимание на то, как определяются data и xAxisLabels, как форматируются метки и как data отображается внутри декоратора для создания полос и кругов.

Не совсем ясно, в чем именно заключалась проблема с вашим кодом, поскольку вы пропустили некоторые важные части, но я думаю, что проблема была в основном связана с тем, как вы настроили свои данные.


Результат выглядит следующим образом:

витрина

person Bas van der Linden    schedule 03.10.2020
comment
Спасибо, а можно прямоугольнику закруглить углы? - person Blake; 04.10.2020
comment
Да, это очень просто. Вам просто нужно установить реквизит rx на Rect. Я обновил свой ответ, чтобы привести пример. - person Bas van der Linden; 04.10.2020