Как получить доступ к имени в метке круговой диаграммы с помощью перезарядок? - PullRequest
1 голос
/ 10 апреля 2019

Проблема:

Я создал круговую диаграмму, используя графики. Но в метке он показывает значение, которое я хочу показать имя данных.

Вот так мой код.

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";

import { Card, CardBody, CardTitle, CardFooter } from "reactstrap";
import { PieChart, Pie, ResponsiveContainer, Cell, Tooltip } from "recharts";

import "./SubscribersByChannelCategory.css";
import { get_device_width } from "../../../actions";

const data01 = [
  {
    name: "Group A",
    value: 50
  },
  {
    name: "Group B",
    value: 700
  },
  {
    name: "Group C",
    value: 700
  },
  {
    name: "Group D",
    value: 200
  },
  {
    name: "Group E",
    value: 278
  },
  {
    name: "Group F",
    value: 189
  },
  {
    name: "Group C",
    value: 300
  },
  {
    name: "Group G",
    value: 200
  },
  {
    name: "Group H",
    value: 278
  },
  {
    name: "Group I",
    value: 189
  }
];

const COLORS = [
  "#65d3da",
  "#79d69f",
  "#fad144",
  "#d76c6c",
  "#138185",
  "#26a0a7",
  "#ec983d",
  "#cbe989",
  "#f9ec86",
  "#ebf898"
];

class SubscribersByChannelCategory extends Component {
  constructor(props) {
    super(props);

    this.getDeviceWidth = this.getDeviceWidth.bind(this);
  }

  componentDidMount() {
    this.getDeviceWidth();
    window.addEventListener("resize", this.getDeviceWidth);
  }

  getDeviceWidth() {
    this.props.get_device_width();
  }

  render() {
    let innerRadius = "50%";
    let outerRadius = "90%";
    let yaspect = 6.0;
    if (this.props.device >= 1024) {
      outerRadius = "95%";
      innerRadius = "70%";
      yaspect = 5.7971;
    }

    if (this.props.device >= 1666) {
      outerRadius = "90%";
      innerRadius = "60%";
      yaspect = 7.297;
    }
    return (
      <div>
        <Card className="subscribers-by-channel-category-card">
          <CardTitle className="subscribers-by-channel-category-card-title">
            Subscribers by Channel Category
          </CardTitle>
          <CardBody>
            <ResponsiveContainer
              width="100%"
              height="100%"
              aspect={5.0 / yaspect}
            >
              <PieChart>
                <Pie
                  data={data01}
                  dataKey="value"
                  nameKey="name"
                  fill="#8884d8"
                  innerRadius={innerRadius}
                  outerRadius={outerRadius}
                  label={true}
                  labelLine={false}
                  cursor="pointer"
                >
                  {data01.map((entry, index) => (
                    <Cell fill={COLORS[index]} key={index}/>
                  ))}
                </Pie>
                <Tooltip content={<CustomTooltip />} />
              </PieChart>
            </ResponsiveContainer>
            <CardFooter className="subscribers-by-channel-category-footer">
              <div>Bring the cursor near to see the details</div>
            </CardFooter>
          </CardBody>
        </Card>
      </div>
    );
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ get_device_width }, dispatch);
}

function mapStateToProps(state) {
  return {
    device: state.device
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SubscribersByChannelCategory);

const CustomTooltip = ({ active, payload }) => {
  if (active) {
    return (
      <div className="subscribers-by-channel-tooltip">
        <p className="subscribers-by-channel-tooltip-title">{payload[0].name}</p>
        <p className="subscribers-by-channel-tooltip-label">{`Channel Category : ${payload[0].name}`}</p>
        <p className="subscribers-by-channel-tooltip-intro">{`Subscribers : ${payload[0].value}`}</p>
        <p className="subscribers-by-channel-tooltip-data">
        {`Share : ${payload[0].value}`}
        </p>
      </div>
    );
  }

  return null;
};

Я много пытался найти решение этой проблемы, но мне не удалось найти какое-либо решение относительно этой проблемы. Может ли кто-нибудь помочь мне решить эту проблему, изменив мой код? Спасибо.

1 Ответ

0 голосов
/ 10 апреля 2019

Существует правильный метод, который может быть полезен.Я не могу повторно отредактировать ваш код.Таким образом, я получил код от повторных испытаний и попробовал это.Вот решение.

const RADIAN = Math.PI / 180;
 const renderCustomizedLabel = ({
  cx,
  cy,
  midAngle,
  innerRadius,
  outerRadius,
  percent,
  index
  }) => {
      const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
      const x = cx + radius * Math.cos(-midAngle * RADIAN);
      const y = cy + radius * Math.sin(-midAngle * RADIAN);

return (
<text
  x={x}
  y={y}
  fill="white"
  textAnchor={x > cx ? "start" : "end"}
  dominantBaseline="central"
>
  {/* {`${(percent * 100).toFixed(0)}%`} */}
  {data[index].name}
</text>
);
};

Вам просто нужно удалить процентную часть и дать ей {data [index] .name} . В вашем случае вы должны использовать data01и это индекс.

Ссылка: Решение для песочницы здесь

...