这是组件的一部分:
import MyComp from '../../lib/MyComp'
const Data = ( { data } ) => (
<div className="data-box" id="data-box">
<MyComp data={data} />
</div>
)
如何获得 MyComp 容器内data-box
div的宽度?
答案 0 :(得分:11)
查看此工作演示:JSFiddle:
var Parent = React.createClass({
render: function() {
return <div id="parent">Hello Parent<Child></Child></div>;
}
});
var Child = React.createClass({
componentDidMount: function() {
alert('Parent width: ' + this.refs.child.parentNode.clientWidth);
},
render: function() {
return <div ref="child">Hello Child</div>;
}
});
声明ref="child"
将使组件本身可以通过this.refs.child
访问该元素。它是vallina节点实例。使用this.refs.child.parentNode.clientWidth
将返回父级的宽度。或者,使用this.refs.child.parentNode.getBoundingClientRect()
。
参考:React refs
答案 1 :(得分:1)
您需要使用反应参考。
在MyComp课上:
class MyComp extends React.Component {
//All your PropTypes and functions...
//New function
newFunction () {
console.log(this.refs.refName);
//This will give you the Data component. There you can call methods to calculate width, or whatever you need to do with that component
}
//Your render function
render() {
return <div ...whatever you have... ref="refName">
}
}
您可以查看react documentation
答案 2 :(得分:0)
应该是什么工作是这样的 MyComp可能看起来像这样
render() {
return <div ref="node"></div>
}
使用this.refs.node
,您将获得当前的dom元素并使用
this.res.node.parentNode
你应该得到parentNode