我有一个 React 组件,它显示 <svg>
.有一个 <text>
随时间变化的属性。我想要 <svg>
增加宽度以显示完整的 text
.如何使跟随组件的大小随文本的长度动态变化?
const S = {
Container: styled.div`
background: red;
width: '10px';
height: '10px';
`
};
export class RectNode extends Component<IRectNodeProps> {
render() {
return (
<S.Container>
<svg width="auto" height="auto">
<rect
x="0"
y="0"
width="100%"
height="100%"
stroke="red"
stroke-width="3px"
fill="white"
/>
// more shapes here
<text
x="50%"
y="50%"
dominant-baseline="middle"
text-anchor="middle"
>
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa
</text>
</svg>
</S.Container>
);
}
}
JS fiddle :
<svg width="auto" height="auto">
<rect
x="0"
y="0"
width="100%"
height="100%"
stroke="red"
stroke-width="3px"
fill="white"
/>
// more shapes here
<text
x="50%"
y="50%"
dominant-baseline="middle"
text-anchor="middle"
>
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa
</text>
</svg>
最佳答案
渲染后获取文本BBox,通过改变状态设置SVG宽度属性。示例 here .
class SvgComponent extends React.Component {
state = {width: 0};
componentDidMount() {
this.updateTextSize();
}
componentDidUpdate() {
this.updateTextSize();
}
updateTextSize() {
const box = this.text.getBBox();
if(this.state.width !== box.width) {
this.setState({width: box.width});
}
}
render() {
return (
<svg width={this.state.width} height="40">
<text ref={handle => this.text = handle} x="50%" y="25" textAnchor="middle">
{this.props.text}
</text>
</svg>
);
}
}
关于html - 使 <svg> 的宽度增长以匹配它的 <text> 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335108/