用React计算SVG边界框?

Ano*_*wie 5 javascript svg reactjs

我正在编写一个使用React生成SVG的可视化应用程序.我需要的一个部分是标签 - 即文本,由一个封闭的盒子包围,带有可变文本,可能是旋转和样式.

所以我有一个组件NodeLabel,目前有固定的尺寸:

render() {
        return <g>
            <rect className="label" x={this.props.x} y={this.props.y-10} width={20} height={40}></rect>
            <text className="labelText" x={this.props.x} y={this.props.y}>{this.props.children}</text>
        </g>
    }
Run Code Online (Sandbox Code Playgroud)

我在DOM中找到了一些关于这样做的信息,这里是:SVG文本周围的矩形边框

但我不太清楚如何将其转换为React组件 - 在render()方法中,没有要查看的DOM元素.我可以使用document.createElement()而不是期望SVG元素的维度正常运行(并尊重CSS)吗?另外,有没有办法避免基本上创建代码的两个副本,一个在JSX中,另一个在此之前用于计算尺寸?(比如,例如,为这个临时的屏幕外拷贝评估JSX到DOM元素的片段)

更新:2018年1月,我又回到了这里:-)实际应用程序是一个开源网络图表工具,目前正在使用GD和PHP,但我希望转向JS,React和SVG.

这里的带宽标签是我想要重现的,尽管节点标签在当前的非SVG版本中使用相同的功能.

这里的带宽标签是我想要重现的,尽管节点标签在当前的非SVG版本中使用相同的功能.

这是我的新的最小例子:

// MyLabel should be centred at x,y, rotated by angle, 
// and have a bounding box around it, 2px from the text.
class MyLabel extends React.Component {
  render() {
    const label = <text x={this.props.x} y={this.props.y} textAnchor="middle" alignmentBaseline="central">{this.props.children}</text>;
        
    // label isn't a DOM element, so you can't call label.getBoundingClientRect() or getBBox()

    // (Magic happens here to find bbox of label..)        
    // make up a static one for now
    let bb = {x: this.props.x-20, y: this.props.y-6, width: 40, height: 12};
    
    // add margin
    const margin = 2;
    bb.width += margin * 2;
    bb.height += margin * 2;
    bb.x -= margin;
    bb.y -= margin;
    
    // rect uses bbox to decide its size and position
    const outline = <rect x={bb.x} y={bb.y} width={bb.width} height={bb.height} className="labeloutline"></rect>;
    
    const rot = `rotate(${this.props.angle} ${this.props.x} ${this.props.y})`;
    // build the final label (plus an x,y spot for now)
    return <g transform={rot}>{outline}{label}<circle cx={this.props.x} cy={this.props.y} r="2" fill="red" /></g>;
  }
}

class Application extends React.Component {
  render() {
    return <svg width={300} height={300}>
      <MyLabel x={100} y={100} angle={0}>Dalmation</MyLabel>
      <MyLabel x={200} y={100} angle={45}>Cocker Spaniel</MyLabel>
      <MyLabel x={100} y={200} angle={145}>Pug</MyLabel>
      <MyLabel x={200} y={200} angle={315}>Pomeranian</MyLabel>
    </svg>;
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<Application />, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)
body { background: gray; }
svg {background: lightgray;}
.labeloutline { fill: white; stroke: black;}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

Mas*_*nes 3

您可以预先计算/测量字体几何形状,并根据输入字符串获得文本尺寸的合理估计(这是最简单的解决方案,但如果字体发生变化,显然会破坏),或者执行两阶段渲染:

\n\n

也就是说,您通过 ref 获取 dom 元素,在挂载上获取框,最后通过更新状态重新渲染,如下所示:

\n\n
class MyLabel extends React.Component {\n  constructor(props){\n    super(props);\n    this.state = {text_extents:null};\n  }\n  componentDidMount() {\n   const box = this.text.getBBox();\n\n   this.setState({text_extents:[box.width,box.height]});\n  }\n render() {\n   const margin = 2;\n   const extents = this.state.text_extents;\n   const label = <text ref={(t) => { this.text = t; }} textAnchor="middle" dy={extents?(extents[1]/4):0} >{this.props.children}</text>;\n   const outline = extents ?\n         <rect x={-extents[0]/2-margin} y={-extents[1]/2-margin} width={extents[0]+2*margin} height={extents[1]+2*margin} className="labeloutline"></rect>\n         : null;\n\n   return <g transform={`translate(${this.props.x},${this.props.y}) rotate(${this.props.angle})`}>{outline}{label}</g>;\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,根据最新的反应文档,这不应导致任何用户可见的闪烁:

\n\n
\n

组件DidMount():在此方法中调用setState()将触发额外的渲染,但它会在浏览器更新屏幕之前发生。这保证了即使在这种情况下 render() 被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题。然而,对于模态和工具提示等情况,当您需要在渲染依赖于其大小或位置的内容之前测量 DOM 节点时,它可能是必要的。

\n
\n\n

最后,请注意,如果标签字符串发生更改(通过 props 或其他方式),您将需要相应地更新范围(通过componentDidUpdate())。

\n