即使在页面加载后使用 ```document.getElementById()``` 在反应中也无法获取元素并不断给出错误?

问题描述 投票:0回答:0

我正在尝试通过天气复选框获取用户输入,用户是否希望从网站获取电子邮件以获取新优惠和更新,但是当我定义元素时它一次又一次地给我错误,我已经尝试过

window.onload()
,
useEffect
,
useRef
hook 但我的元素一直出错,它说
Cannot read properties of undefined (reading 'checked')
,

这是代码。

getElementById()

  let wantEmailAndUpdates;
  useEffect(() => {
    if (document.getElementById("wantEmailAndUpdates").checked) {
        wantEmailAndUpdates = document.getElementById("wantEmailAndUpdates").value;
    }
  }, [])

输入密码

<label className="ContactInformationFormAccountEmailTitleEmailNewsCheckbox">
    <input type="checkbox" value={true} id='wantEmailAndUpdates' name='wantEmailAndUpdates' checked />
    Email me with news and offers
</label>

useRef
挂钩:

  const wantEmailAndUpdatesRef = useRef(null)
  useEffect(() => {
    if (wantEmailAndUpdatesRef.current.focus().checked) {
      wantEmailAndUpdates = wantEmailAndUpdatesRef.current.focus().value;
    }
  }, [])

输入密码

<label className="ContactInformationFormAccountEmailTitleEmailNewsCheckbox">
    <input type="checkbox" value={true} ref={wantEmailAndUpdatesRef} id='wantEmailAndUpdates' name='wantEmailAndUpdates' checked />
    Email me with news and offers
</label>
reactjs dom react-hooks
© www.soinside.com 2019 - 2024. All rights reserved.