【问题标题】:add text inside a rect in force layout graph d3.js REACTJS在强制布局图 d3.js REACTJS 中的矩形内添加文本
【发布时间】:2015-09-01 15:51:52
【问题描述】:

我正在尝试使用 ReactJS 在矩形中间显示文本。我已经尝试了不同的方法,但文本总是出现在右侧的图表之外。

我正在尝试执行以下操作: http://bl.ocks.org/mbostock/7341714

我得到以下结果:

如何让数字 60 出现在矩形的中间?

这是我的代码:

   var BarChart = React.createClass({

      getInitialState: function () {
        return {props: this.props};
      },

      componentWillReceiveProps: function(nextProps) {
        this.setState({
          props: nextProps
        });
      },

      render: function() {
        return (
          <svg width={this.state.props.width} height={this.state.props.height}>
            <g  style={{strokeWidth:4, stroke:"black"}}>
              <rect fill={"white"} width={146} height={18}/>  
              <text> {this.state.props.propValue} </text>
            </g>
          </svg>
        );
      }

【问题讨论】:

  • 如果我将 {this.state.props.propValue} 替换为非 React JS 变量,我只能在栏内添加文本。如果我用简单的字母替换它,文本将正确显示在里面。

标签: javascript d3.js reactjs


【解决方案1】:

我找到了解决方案,但我不知道为什么会出现这个问题。 &lt;text&gt; &lt;/text&gt; 里面的值必须是字符串值,{this.state.props.propValue} 是整数。

我将 .toString() 添加到 {this.state.props.propValue} 并解决了我的问题。

这是最终结果:

已解决的代码:

     render: function() {
        var val = this.state.props.propValue;
        return (
          <svg width={this.state.props.width} height={this.state.props.height}>
            <g style={{strokeWidth:2, stroke:"black"}}>
             <rect fill={"white"} width={146} height={18}  y={1} x={1}/>
            </g>
            <DataSeries data={this.state.props.propValue} width={w} height={h} color={this.state.props.propColor} /> 
            <text> {val.toString()} </text>
          </svg>
        );

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2013-02-12
    相关资源
    最近更新 更多