[英]Access to a several elements through one ref React
I wanna get access to multiple elements with using refs
feature. 我想使用
refs
功能访问多个元素。 Then after I could iterate through elements of this.tabs
. 然后我可以遍历
this.tabs
元素。 Code below doesn't work, how fix it to make work? 下面的代码不起作用,如何解决它的工作? Solution, which I use now is
document.querySelectorAll('tabs')
, but it doesn't seems right for React. 我现在使用的解决方案是
document.querySelectorAll('tabs')
,但它似乎不适合React。
class Comp extends React.Component { constructor(props) { super(props); this.tabs = React.createRef(); } componentDidMount() { console.log(this.tabs); } render() { return ( <div> <span class="tab" ref={this.tabs}>One</span> <span class="tab" ref={this.tabs}>Two</span> <span class="tab" ref={this.tabs}>Three</span> </div> ); } } ReactDOM.render( <Comp />, document.getElementById('app') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>
You're assigning refs
incorrect way. 你分配
refs
方式不正确。 Do it in the early beginning of render()
method: 在
render()
方法的早期开始:
this.tabs = []
refs are going to be assigned via refs将通过分配
<span className="tab" ref={(tab) => { this.tabs.push(tab) }}>One</span>
I hope you could call this.tabs
this case! 我希望你能
this.tabs
这种情况下调用this.tabs
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.