我正在渲染带有标签的 SVG 组件。这些标签组件需要根据它们的文本内容(以及它们的大小)正确布局,以避免自身重叠。
为了获得每个标签的实际大小,每次更新标签内容时似乎都需要双重渲染。
在标签组件级别,我需要
- 第一次渲染它
- 检索真实 SVG DOM 节点的边界框
- 出于性能原因缓存边界框
- 重新渲染组件以根据其缓存的边界框调整标签位置
然后,在每次重绘时:
- 根据缓存的边界框渲染
- 比较之前和更新的 props 之间的标签内容,如果更改:
- 更新和缓存标签边界框
- 根据更新和缓存的边界框重新渲染
到目前为止,这是我实现标签组件的方式:
var Label = React.createClass({
updateBBox: function() {
// Trigger re-rendering
this.setState({
bbox: this.getDOMNode().getBBox()
});
},
componentDidMount: function() {
// Will trigger a re-rendering at mount
this.updateBBox();
},
componentDidUpdate: function(prevProps, prevState) {
// If content has changed, re-render
if (this.props.content !== prevProps.content) {
this.updateBBox();
}
},
render: function() {
// Render according to size from current bounding box if any cached
// ...
}
});
所以,我的问题不是关于算法,而是关于是否有更好的 React 兼容方式来实现这一点。是否使用状态来缓存 React 方式中允许的这种缓慢的“计算”或 DOM 访问?双重渲染对于 React 来说是一种不寻常的情况吗?