【问题标题】:In JavaScript, cannot document.getElementById is null even if the element is in the DOM在 JavaScript 中,即使元素在 DOM 中,document.getElementById 也不能为 null
【发布时间】:2017-03-27 07:21:58
【问题描述】:

在 React 中,我使用了一个组件,它有 <input type="text" id="location" />。当DOM加载组件时,在组件的componentDidMount()中,我会尝试搜索元素。

componentDidMount(){
    debugger;
    let ele = document.getElementById('location');
    console.log('ele', ele)
}

当它在 debugger 处中断时,我查看 DOM(Chrome 中的元素选项卡),上面的输入元素已经存在,但 ele 在控制台中仍然为空。

为什么?该元素已加载到 DOM 中,但我仍然找不到它? 谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您的代码应该可以工作。但是你为什么要使用 jquery 方法呢? ReactDom.findNode 就是为了这个。您可以添加ref 来访问该元素。

    componentDidMount(){
        debugger;
       var Value = React.findDOMNode(this.refs.location).value;
        console.log('ele', ele)
    }
    
    <input type="text" ref="location" />
    

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 2023-03-28
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2014-03-15
      相关资源
      最近更新 更多