首页 > 解决方案 > 如何使用 React 在标签中设置 img?

问题描述

我正在使用react-chartist. 在标签上,我想在标签文本旁边添加图像。我尝试了所有想法,但都没有奏效。一切回归[object Object]。这个问题是否有很好的解决方案?我也可以使用 just 添加标签css,但如果我可以在<Chartist />组件内部添加标签,那就容易多了。

我尝试的简单代码示例(下面的代码沙盒演示):

class Chart extends React.Component {
  render() {
    const labels = ["label 1", "label 2", "label 3"];
    const images = [
      "http://placekitten.com/100/100",
      "http://placekitten.com/101/101",
      "http://placekitten.com/102/102"
    ];
    const series = [[40, 30, 20]];

    const labelsInsideReactFragment = labels.map((el, key) => (
      <React.Fragment>
        <img src={images[key]} /> {el}
      </React.Fragment>
    ));

    const labelsViaGhIssue = labels.map((el, key) => {
      return {
        label: el,
        image: images[key]
      };
    });

    const labelsInsideDiv = labels.map((el, key) => (
      <div>
        <img src={images[key]} /> {el}
      </div>
    ));

    const labelsOnlyImg = labels.map((el, key) => <img src={images[key]} />);

    const data1 = {
      labels,
      series
    };

    const data2 = {
      labels: labelsViaGhIssue,
      series
    };

    const data3 = {
      labels: labelsInsideDiv,
      series
    };

    const data4 = {
      labels: labelsInsideReactFragment,
      series
    };

    const data5 = {
      labels: labelsOnlyImg,
      series
    };

    const options = {
      height: "200px",
      width: "500px"
    };

    return (
      <div>
        <ChartistGraph data={data1} options={options} type="Bar" />
        <ChartistGraph data={data2} options={options} type="Bar" />
        <ChartistGraph data={data3} options={options} type="Bar" />
        <ChartistGraph data={data4} options={options} type="Bar" />
        <ChartistGraph data={data5} options={options} type="Bar" />
      </div>
    );
  }
}

演示:https ://codesandbox.io/s/chartist-8oeju

我还在jsbinhttpsReact ://jsbin.com/gulokelide/edit?js,output 上找到了这个演示,但我猜 它不起作用。

标签: javascriptreactjschartist.jsreact-chartist

解决方案


根据您提供的 jsbin 链接,我们也可以更新 react 版本。

检查我创建的新沙箱。

https://codesandbox.io/s/chartist-m1yv9

方法是:每个 react chartist 组件都附加了它的 chartist 对象。所以添加一个 ref 来捕获它并从每个图表的上下文中更新标签,就像 jsbin 示例一样。

import Chartist from "chartist";

//in componentDidMount()
      const chart = this.refTwo.current;
      chart.chartist.on("draw", context => {
        if (context.type === "label" && context.axis.units.pos === "x") {
          if (context.text && context.text.image) {
            const group = new Chartist.Svg("g");
            group.append(
              new Chartist.Svg("image", {
                "xlink:href": context.text.image,
                width: "30px",
                height: "30px",
                x: context.x + 55,
                y: context.y + 5
              })
            );

            context.element.replace(group);
          }
        }
      });


// in render()
<ChartistGraph
          ref={this.refTwo}
          data={data2}
          options={options}
          type="Bar"
 />


推荐阅读