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