简体   繁体   中英

TypeError: Cannot read property 'addEventListener' of null in ReactJS

I have already tried inserting the script tag in my index.html after the closing body tag.

I have also tried changing myForm.addEventListener('submit', addRecord); to document.addEventListener('submit', addRecord); and it just changed but still throws the same null error in the if(nameInput.value === '' || jobInput.value === '') of the addRecord function in my main.js

main.js

const myForm = document.querySelector('#my-form');
const nameInput = document.querySelector('#name');
const jobInput = document.querySelector('#job');
const employeeList = document.querySelector('#employeeList');

myForm.addEventListener('submit', addRecord);

export function addRecord() {

    if(nameInput.value === '' || jobInput.value === '') {
        alert('Please complete all the fields.');
    } 
    else {
        const li = document.createElement('li');
        li.appendChild(document.createTextNode(`${nameInput.value} (${jobInput.value})`));
        employeeList.appendChild(li);
        nameInput.value = "";
        jobInput.value = "";
    }
}

export function clearFields() {
    nameInput.value = "";
    jobInput.value = "";
}

app.js

import React from 'react';
import './App.css';
import { addRecord, clearFields } from './main.js';

function App() {
  return (
    <div className="main-container">
        <table className="main">
            <tr className="split">
              <td>
                <div className="left">
                  <form id="my-form">
                    <label for="name">Name:</label><br />
                      <input className="text" type="text" id="name" /><br /><br />
                      <label for="job">Job Detail:</label><br />
                      <input className="text" type="text" id="job" /><br /><br />
                      <input className="btn-add" type="submit" value="Add" onclick={addRecord()}/>
                      <input className="btn-clear" type="button" value="Clear" onclick={clearFields()} />
                  </form>  
                </div>
              </td>
              <td>
                <div className="right">
                  <p>Employee List</p>
                  <ul className="employeeList" id="employeeList"></ul>
                </div>
              </td>
            </tr>
        </table>
    </div>
  );
}

export default App;

In React you can use Formik to handle your form.

But if you really want to do like this you have to put your scripts in componentDidMount or useEffect, because you are selecting an element that is not rendered yet in dom so you get this error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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