代码之家  ›  专栏  ›  技术社区  ›  Nelson Silva

访问HTMLcollection时获取null

  •  1
  • Nelson Silva  · 技术社区  · 7 年前

    为了给他们标题,我有4个带列表的选项卡。我想访问每个选项卡的标题,但我只能访问整个HTMLcollection。使用react。

    import React from 'react';
    import {Component} from 'react';
    
    class tabs extends Component {
    
        render() {
            return (
                <div className={"tabs"}>
                    <ul>
                        <li><a>Class 1</a></li>
                        <li><a>Class 2</a></li>
                        <li><a>Class 3</a></li>
                        <li><a>Class 4</a></li>
                    </ul>
    
                    {console.log(document.getElementsByTagName("li"))};
                    //full collection with length of 4
    
                     {console.log(document.getElementsByTagName("li").length)};
                     //0
    
    
           {console.log(document.getElementsByTagName("li").item(0).innerHTML)};
                      //"Cannot read property 'innerHTML' of null"
    
                </div>
            )
        }
    }
    
    export default tabs;
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Tomasz Mularczyk    7 年前

    这是因为当您声明JSX时,它不会立即打印到DOM中。首先,它将由巴贝尔传送,然后 render hook React将更新DOM。但是,嘿,在这中间,您已经尝试访问这些DOM元素了。。。

        2
  •  1
  •   Tyler Sebastian    7 年前

    你到底想做什么?如果你只想知道 li 在某个时候,使用 ref

    class Component extends React.Component {
      componentDidMount() {
        console.log(this.el.children.length) // 4
      }
    
      render() {
        return (
          <ul ref={ el => this.el = el }>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
          </ul>
        )
      }
    }