React中的getElementById [英] getElementById in React

查看:816
本文介绍了React中的getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此错误此刻:

Uncaught TypeError: Cannot read property 'value' of null

我在下面的渲染函数中调用它:

I call this in my render function below:

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData}/>

我也尝试过在这里打电话

I also have tried calling it in here

componentWillMount: function(){
        var name = document.getElementById('name').value;
      },

如何获取输入文本字段的ID并读取该值,并确保该值不为null?

How can I get the id of an input text field and read that value and ensure it is not null?

我认为在尝试读取元素后DOM正在加载,因此为什么它为空

I think the DOM is loading after I try to read the element hence why it is null

推荐答案

您需要在componentDidMount生命周期中使用您的函数,因为这是加载DOM时调用的函数.

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

利用refs访问DOM元素

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

有关此信息,请参见

See this answer for more info on How to access the dom element in React

这篇关于React中的getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆