Svg 如何使父组件包含子组件

Svg 如何使父组件包含子组件,svg,reactjs,Svg,Reactjs,我正在用reactjs和svg编写一个模型查看器。我想让父组件包含一组子组件 子组件将根据其标签文本宽度自动调整大小。但是,为了计算最小的封闭矩形,父组件应该如何访问子大小 问题似乎在于如何在组件层次结构中向上传递信息 // child automatically sized after text width var Child = React.createClass({ componentDidMount: function () { var rect = this.r

我正在用reactjs和svg编写一个模型查看器。我想让父组件包含一组子组件

子组件将根据其标签文本宽度自动调整大小。但是,为了计算最小的封闭矩形,父组件应该如何访问子大小

问题似乎在于如何在组件层次结构中向上传递信息

// child automatically sized after text width
var Child = React.createClass({
    componentDidMount: function () {
        var rect = this.refs.rect.getDOMNode();
        var text = this.refs.text.getDOMNode();
        rect.setAttribute('width', text.offsetWidth + 8);
    },
    render: function() {
        return <g transform={'translate(' + this.props.x + ', ' + this.props.y + ')'}>
            <rect ref="rect" height={50} fill="#cfc"/>
            <text ref="text" x={4} y={15}>{this.props.text}</text>
        </g>;
    }
});

// parent that I want to automatically enclose all children
var Parent = React.createClass({
    render: function() {
        return <g>
            <rect x={10} y={10} width={200} height={100} fill="#ccf"/>
            <Child text="first child" x={20} y={20}/>
            <Child text="second child" x={180} y={80}/>
          </g>;
    }
});

var Diagram = React.createClass({
    render: function() {
        return <svg width={300} height={250}><Parent/></svg>;
    }
});

React.render(<Diagram/>, document.getElementById('container'));
//子项在文本宽度后自动调整大小
var Child=React.createClass({
componentDidMount:函数(){
var rect=this.refs.rect.getDOMNode();
var text=this.refs.text.getDOMNode();
rect.setAttribute('width',text.offsetWidth+8);
},
render:function(){
回来
{this.props.text}
;
}
});
//要自动包含所有子项的父项
var Parent=React.createClass({
render:function(){
回来
;
}
});
var Diagram=React.createClass({
render:function(){
回来
}
});
React.render(,document.getElementById('container');

尝试此处的代码。

您是否尝试过事件(在计算宽度时,向父级发起事件)?向上通信:回调。调用回调函数,将其宽度值提供给父级,并保留宽度列表。这样,当宽度值发生变化时,您总是知道宽度值。@JeremyD:回调成功了!但是,在哪里存储列表是最好的?对我来说,这似乎不是国家或道具的一部分,但我是新的反应。家长需要知道这些宽度的权利?因此,我将以父级的状态存储。我应该创建一个答案吗?@JeremyD如果你有时间的话,最好是一个带JSFIDLE的答案。