React中为type=date的input设置日期值报null错误如何解决
报错原因
- 你的代码是React组件代码,你直接在组件return渲染逻辑前调用
minimumSetDate(),此时组件的DOM节点还没有被渲染挂载到页面上,document.getElementById("remindDate")无法找到对应元素,返回结果为null,对null访问value属性就会触发你遇到的类型错误。 - W3Schools的示例代码是在页面DOM已经加载完成后执行的,所以可以正常获取到元素完成赋值,和你的代码执行时机完全不同。
修复方案
推荐使用React原生的状态管理和生命周期钩子实现需求,避免直接操作DOM:
- 首先引入React的
useState和useEffect钩子 - 用状态管理日期输入框的值,在组件挂载完成后设置默认日期
- 给input的value属性绑定状态,配合onChange实现受控组件
修复后的代码示例:
import { useState, useEffect } from 'react'; export default function NewNoteModal() { // 声明日期状态 const [remindDate, setRemindDate] = useState(''); // 组件挂载完成后设置默认日期 useEffect(() => { let today = new Date(); let day = String(today.getDate()).padStart(2, '0'); let month = String(today.getMonth() + 1).padStart(2, '0'); let year = today.getFullYear(); let currentDate = `${year}-${month}-${day}`; setRemindDate(currentDate); }, []); return( <div id = "newNoteModal"> <div id = "newNote-header"> <h2>NoteKeeper</h2> </div> <form id = "newNote-content"> <label htmlFor = "noteName">Note Name:</label> <input type="text" id = "noteName"></input> <br></br> {/* ---------------------- */} <label htmlFor="checkB-important">Important:</label> <input type="checkbox" name="important" value="important" id = "checkB-important"></input> <br></br> {/* ---------------------- */} <label htmlFor="remindDate">Remind me on:</label> {/* 绑定状态和变更事件 */} <input type="date" name="remindDate" id = "remindDate" value={remindDate} onChange={(e) => setRemindDate(e.target.value)} ></input> <br></br> {/* ---------------------- */} </form> </div> ); }
如果你一定要用原生DOM操作的方式,也可以把赋值逻辑放到useEffect回调中,保证组件挂载完成后再执行即可,不过该写法不符合React的设计思想,不推荐使用。
内容的提问来源于stack exchange,提问作者king60096009
相关产品推荐
相关产品推荐

