我用 next.js 編碼登錄:
import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Router from 'next/router'
import * as React from 'react'
const Home: NextPage = () => {
const [disable, setDisable] = React.useState(false);
const loginUser = async (e: any) => {
try {
setDisable(true)
const y = (window.document.getElementById('inputUsername'))
let inputValue = window.document.getElementById('inputUsername').value
console.log(inputValue)
const resp = await fetch('/api/token/valid')
const data = await resp.json()
if (data.token) {
//Router.push('/dashboard')
setDisable(false)
}
} catch (err) {
// Handle Error Here
console.error(err);
}
};
return (
<div className={styles.container}>
<Head>
<title>Login - Uhrenlounge CMS</title>
<meta name="description" content="Generated by create next app" />
</Head>
<main className={styles.main}>
<form className="p-3 mb-2 bg-secondary text-white">
<div className="text-center">
<h1>Uhrenlounge CMS</h1>
</div>
<hr />
<div className="mb-3">
<label className="form-label">Benutzername</label>
<input
type="text"
className="form-control"
id="inputUsername"
name="inputUsername"
placeholder="Benutzername"
required
/>
</div>
<div className="mb-3">
<label className="form-label">Passwort</label>
<input type="password" className="form-control" id="inputPassword" placeholder="Passwort" />
</div>
<div className="d-grid gap-2">
<button type="button" disabled={disable} onClick={loginUser} className="btn btn-primary" id="btnLoginUser">Login</button>
</div>
</form>
</main>
</div>
)
}
export default Home
我想在單擊按鈕后獲取輸入的值。我嘗試使用此代碼獲取值:
let inputValue = window.document.getElementById('inputUsername').value
VSCode 給我這個錯誤:物件可能是“空”。
我不知道我能做什么。有沒有人有任何想法或解釋如何在 onclick 后訪問該值?
uj5u.com熱心網友回復:
它只是告訴您,如果沒有 id 為 'inputUsername' 的元素getElementById將回傳 null 而不是您期望的值。
您可以根據需要處理或忽略這種情況。
但是,如果您真的需要在 react 中訪問 dom 節點,那么正確的方法是 hooks https://reactjs.org/docs/hooks-intro.html。如果兩個組件同時存在,由于 id 重疊,您的組件現在可能無法作業。
uj5u.com熱心網友回復:
好吧,把它想象成假設沒有找到具有該 ID 的元素,那么該函式將回傳沒有 value 屬性的 null。解決這個問題的最簡單方法是使用 ? 為您執行空檢查的運算子。
let inputValue = window.document.getElementById('inputUsername')?.nodeValue || "no value"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370046.html
標籤:javascript 反应 打字稿 下一个.js
