【问题标题】:Getting null when accessing to HTMLcollection访问 HTMLcollection 时获取 null
【发布时间】:2018-03-19 17:11:51
【问题描述】:

我有 4 个带有列表的选项卡,以便为它们提供标题。我想访问每个选项卡的标题,但我只能访问整个 HTMLcollection。使用反应。

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;

【问题讨论】:

  • 这对我有用
  • XY Problem。正确的解决方案可能根本不包括访问 DOM。

标签: javascript html reactjs tabs htmlcollection


【解决方案1】:

那是因为当你声明 JSX 时,它不会立即被打印到 DOM 中。首先,它将由 Babel 转译,在 render 钩子之后,React 将更新 DOM。但是,嘿,在这中间你试图访问这些 DOM 元素...

【讨论】:

  • 那么,我应该什么时候尝试访问 DOM 呢? componentDidMount ?
  • @NelsonSilva 完全正确! reactjs.org/docs/react-component.html#componentdidmount - “需要 DOM 节点的初始化应该放在这里”
  • 成功了,谢谢!仍然习惯于响应生命周期钩子
  • @NelsonSilva 真正的问题是:你为什么认为你需要访问 DOM。通常你应该避免直接访问 DOM 或者至少使用refs。这似乎是the XY problem
  • 我同意你不应该依赖直接访问 DOM,除非你正在使用第三方库。
【解决方案2】:

你到底想做什么?如果您只是想在某个时候获得lis 的数量,请使用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>
    )
  }
}

【讨论】:

  • 我想将其中的文本传递给一个方法,以便我可以根据我所在的选项卡做一些事情。
  • @TylerSebastian 来自柏林的亲切问候 :) 现在吃晚饭。
  • @TylerSebastian 这实际上不是我说的。我说应该是this.el.children.lengthString refs are deprecated 并且可能会在未来的 react 版本中被删除。我永远不会推荐使用它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 2016-08-23
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 1970-01-01
相关资源
最近更新 更多