![](/img/trans.png)
[英]this.refs = undefined in react with babel env settings “last 2 chrome versions”
[英]Why does `this.refs` return undefined in this simple example?
在下面的示例中this.refs.foo.clientWidth
返回undefined
,我無法弄清楚原因。 如何在PageComp
獲取SomeComp
的引用來使用它的寬度? (使用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
返回React Element。 但是如果你想使用DOM元素 - 你需要找到這個節點
React 15.0.1需要以下語法 : ReactDOM.findDOMNode(this.refs.foo)
JSBIN: http ://jsbin.com/xabidaquti/1/edit?html,js,console,output
為了更清晰,如果將refs
設置為div
, input
等html元素, this.refs.foo.clientWidth
將起作用。 因為refs
本身會在這樣的html元素的情況下返回DOM節點。
如果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.