[英]Why does `this.refs` return undefined in this simple example?
In the following example this.refs.foo.clientWidth
returns undefined
and I can't figure out why. 在下面的示例中this.refs.foo.clientWidth
返回undefined
,我无法弄清楚原因。 How can I get the reference to SomeComp
in PageComp
to use its width? 如何在PageComp
获取SomeComp
的引用来使用它的宽度? (using React 15.2.1 or similar) (使用React 15.2.1或类似)
class PageComp extends React.Component {
componentDidMount() {
console.log(this.refs.foo.clientWidth);
}
render() {
return (
<div>
<p>{this.props.name}</p>
<SomeComp ref="foo" />
</div>
);
}
}
class SomeComp extends React.Component {
render() {
return (
<div>
<h1>I loaded</h1>
</div>
);
}
}
ReactDOM.render(
<PageComp name="Joe Schmoe"/>,
document.getElementById('react_example')
);
this.refs.foo
returns React Element. this.refs.foo
返回React Element。 But if you want to work with DOM element - you need to find this Node 但是如果你想使用DOM元素 - 你需要找到这个节点
React 15.0.1 Requires this syntax : ReactDOM.findDOMNode(this.refs.foo)
React 15.0.1需要以下语法 : ReactDOM.findDOMNode(this.refs.foo)
JSBIN: http://jsbin.com/xabidaquti/1/edit?html,js,console,output JSBIN: http ://jsbin.com/xabidaquti/1/edit?html,js,console,output
For better clarity, this.refs.foo.clientWidth
will work if the refs
is set to html elements like div
, input
and so on. 为了更清晰,如果将refs
设置为div
, input
等html元素, this.refs.foo.clientWidth
将起作用。 As refs
by itself will return the DOM Node in case of such html elements. 因为refs
本身会在这样的html元素的情况下返回DOM节点。
If the refs
is set to some React components, then we can access the DOM Node of the Components only using ReactDom.findDOMNode(this.refs.foo)
and hence we need to get the clientWidth
using ReactDom.findDOMNode(this.refs.foo).clientWidth
. 如果refs
设定一些反应的组分,那么我们只能访问使用组件的DOM节点ReactDom.findDOMNode(this.refs.foo)
因此我们需要得到clientWidth
使用ReactDom.findDOMNode(this.refs.foo).clientWidth
。
试试这个ReactDOM.findDOMNode(this.refs["foo"].clientWidth)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.