为什么我无法获取我的this.refs.children元素?

时间:2019-05-04 13:18:40

标签: javascript reactjs

我试图在React中获取ref的元素,但是console.log返回未定义。

这里是情况的直观日志:

here we can see the HTML collection have well some element,but when call then, there is a problem: the console returns undefined

在此图像中,我们可以第一次看到HTML集合中有一些元素,但是当我尝试调用arrayElement时,出现了一个问题:控制台返回未定义的

这是我的代码:

let sliderContainer= this.refs.sliderContainer
console.log("sliderContainer: ", sliderContainer) // return reference element with all property inside
console.log("sliderContainer.childNodes: ", sliderContainer.childNodes,sliderContainer.children ) // return NodeList, HTMLCollection.... length 4
console.log("sliderContainer.childNodes[0]: ", sliderContainer.childNodes[0], sliderContainer.children[0) // return undefined, undefined 

自从控制台在第一个日志中向我显示我引用的组件内的所有div元素之后,怎么可能?

任何提示都会很棒, 谢谢

1 个答案:

答案 0 :(得分:2)

它是HTMLCollection,它像数组一样工作,因此您可以通过索引collection[index]访问元素。有关更多信息,请参见this page