【问题标题】:Recharts custom labelRecharts 自定义标签
【发布时间】:2017-02-02 20:46:09
【问题描述】:

React Recharts 的自定义标签不适用于条形图。

http://jsfiddle.net/xpko4e7e/

 <Bar dataKey="pv"  fill="#8884d8"  label={<CustomLabel/>} />

预计会在所有条形图上看到“标签”文本。

更新
例如,如果我有一个图表,其中有多条线,并且每条线都有一些 label 但在渲染时一些值高于另一个。如何克服这个问题?

Image Preview

【问题讨论】:

    标签: reactjs charts recharts


    【解决方案1】:

    不要返回 div,而是尝试返回文本 SVG 元素

    const CustomizedLabel = React.createClass({
      render () {
        const {x, y, stroke, value} = this.props;
    		
       	return <text x={x} y={y} dy={-4} fill={stroke} fontSize={10} textAnchor="middle">{value}</text>
      }
    });

    然后添加

    &lt;Bar dataKey="pv"  fill="#8884d8"  label={customLabel} /&gt;

    就像我在这里所做的那样,http://jsfiddle.net/CharukaK/6u08o2oa/1/

    【讨论】:

    • 为了让它有更远的距离,可以使用x={(entry.x - entry.cx) * 1.2 + entry.cx} y={(entry.y - entry.cy) * 1.2 + entry.cy}
    【解决方案2】:

    我知道这个问题有点老了,但问题仍然存在。我们不能直接将 HTML 元素用于自定义标签。只有 SVG 元素在工作。但是……

    SVG 支持的元素叫做&lt;foreignObject&gt;

    所以这样的事情会起作用:

    const CustomLabel  = React.createClass({ 
      render() {  
            return (
              <g>
                <foreignObject x={0} y={0} width={100} height={100}>
                  <div>Label</div>
                </foreignObject>
              </g>
            );
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2018-08-31
      • 2021-05-18
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2023-03-24
      • 2012-07-13
      • 1970-01-01
      相关资源
      最近更新 更多