[英]React - can't get this.refs
I am using React 0.14.7. 我正在使用React 0.14.7。 Inside my render I am trying to access ref "progressBar", but without success ( I get 'undefined' in the console ).
在我的渲染器内部,我试图访问ref“ progressBar”,但没有成功(我在控制台中获得“未定义”)。 what am I doing wrong?
我究竟做错了什么?
let element = this.refs.progressBar;
console.log( element );
element.style.transform = 'rotate('+ deg +'deg)';
return(
...
<div className="bar-progress">
<div className="bar-progress-fill" ref="progressBar"></div>
</div>
...);
That happens because refs
are not available in initial render
as you are trying to access it even before its created. 发生这种情况的原因是,在您尝试访问
initial render
, refs
在initial render
中不可用。 You should be doing it in the componentDidMount
function, if you only want to do it once or add it with a condition in componentDidUpdate
as React Docs warns you to not use it in render. 你应该做的
componentDidMount
功能,如果你只想做一次,或者在一个条件添加它componentDidUpdate
作为阵营文档警告你不使用它的渲染。
NOTE: React docs suggesst you on using the callback approach for refs over string approach See this documentation 注意:React文档建议您使用回调方法获取对字符串方法的引用请参阅此文档
So modify your code like 所以像这样修改你的代码
class App extends React.Component { state = { count: 0 } componentDidMount(){ var deg = 30; let element = this.progressBar; console.log( element ); element.style.transform = 'rotate('+ deg +'deg)'; this.setState({count: 1}); } render() { console.log(this) return( <div className="bar-progress"> <div className="bar-progress-fill" ref={(pb) =>this.progressBar=pb}></div> </div> ); } } ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js"></script> <div id="app"></div>
You can not access refs
inside render()
. 您不能访问
render()
内的refs
。 Refs
is accessable only inside react lifecycle methods. Refs
是accessable只有内部反应生命周期方法。
In your case you should use componentDidUpdate() lifecycle method. 在您的情况下,应使用componentDidUpdate()生命周期方法。
componentDidUpdate() {
let element = this.refs.progressBar;
console.log( element );
element.style.transform = 'rotate('+ deg +'deg)';
}
EDIT 1 : ref
is accessable inside render()
, but refs
are not available in initial render. 编辑1 :
ref
可在render()
内部访问,但refs
在初始渲染中不可用。 Please refer the link for more details. 请参阅链接以获取更多详细信息。
Example: Fiddle 示例: 小提琴
DOC: https://zhenyong.github.io/react/docs/more-about-refs.html#cautions DOC: https : //zhenyong.github.io/react/docs/more-about-refs.html#cautions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.