简体   繁体   English

TypeError:无法读取null的属性“值” reactjs |

[英]TypeError: Cannot read property 'value' of null | reactjs |

I've 2 textboxes and 1 button as material UI components. 我有2个文本框和1个按钮作为用户界面组件。

 </p>
        <TextField id="chatidField" />
        <br />
        <p>
          <code>Enter Your Name:</code>
          <hr />
        </p>
        <TextField id="nameField" />
        <br />
        <br />
        <Button
          variant="contained"
          color="secondary"
          onClick={addToFirebase()}
        >
          Get Your Token
        </Button>

the function that onClick calls is as follows: onClick调用的功能如下:

  function addToFirebase() {
  var chatid = document.getElementById("chatidField").value;
  var name = document.getElementById("nameField").value;
  console.log(chatid, name);
 }

I keep getting the following error: 我不断收到以下错误:

TypeError: Cannot read property 'value' of null TypeError:无法读取null的属性“值”

8 | 8 | var chatid = document.getElementById("chatidField").value; var chatid = document.getElementById(“ chatidField”)。value;

9 | 9 | var name = document.getElementById("nameField").value; var name = document.getElementById(“ nameField”)。value;

full code: https://codesandbox.io/s/pqmrn4x 完整代码: https//codesandbox.io/s/pqmrn4x

You have an error in your onClick handler, it should be addToFirebase not addToFirebase() : 您的onClick处理程序中有一个错误,应该是addToFirebase而不是addToFirebase()

<Button
      variant="contained"
      color="secondary"
      onClick={addToFirebase}
    >

When you include () , it will run the addToFirebase function, and use the return value as the onClick handler. 当包含() ,它将运行addToFirebase函数,并将返回值用作onClick处理程序。 In addition, if the addToFirebase() function is a part of your class, you will likely need to use this.addToFirebase instead. 另外,如果addToFirebase()函数是类的一部分,则可能需要使用this.addToFirebase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM