如何在NextJS中实现数组元素存在性校验及弹窗提示?
实现数字数组存在性检查功能
先修正你代码里的基础问题,再补充点击事件逻辑:
- 代码中使用了
<Head>组件但未导入,NextJS需从next/head引入该组件 - React中推荐用
useState管理输入框值,避免直接操作DOM - 按钮点击时要阻止表单默认提交行为,防止页面刷新
完整实现代码
import Head from 'next/head'; import { useState } from 'react'; export default function Home() { const arr = [1, 2, 3, 4, 5, 6]; // 用状态绑定输入框值 const [inputValue, setInputValue] = useState(''); // 点击事件处理函数 const handleCheck = (e) => { // 阻止表单默认提交 e.preventDefault(); // 转换输入为数字类型 const inputNum = Number(inputValue); // 手动遍历数组判断存在性 let isExist = false; for (let num of arr) { if (num === inputNum) { isExist = true; break; } } // 弹窗提示结果 alert(isExist ? `数字${inputNum}在数组中` : `数字${inputNum}不在数组中`); }; return ( <div> <Head> <title>白名单检查器</title> <meta name="description" content="machal" /> <link rel="icon" href="/favicon.ico" /> </Head> <form onSubmit={handleCheck}> <div className='mb-3 pb-2 flex flex-column items-center justify-center'> <div> <label htmlFor="first_name" className="block mb-4 font-medium text-gray-900 dark:text-white text-lg">WHITELIST CHECKER</label> {/* 绑定状态与输入框,限制仅输入数字 */} <input type="number" id="first_name" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white mb-2 dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="输入数字" required value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <div className='flex flex-column'> <button type="submit" className='p-2 mt-2 inline-flex text-center ml-12 w:4/5 text-rose-500 hover:bg-rose-500 hover:text-white ease-in-out'>CHECK</button> </div> </div> </div> </form> </div> ) }
关键说明
- 将输入框类型设为
number,限制用户仅能输入数字,减少非数字输入的判断成本 - 用
useState绑定输入框值,遵循React状态管理规范,避免直接操作DOM元素 - 手动实现数组遍历判断(满足你要求的遍历需求),也可简化为
const isExist = arr.includes(inputNum),效果一致 - 通过表单
onSubmit绑定提交逻辑,按钮设为submit类型,同时支持点击按钮和回车提交
内容的提问来源于stack exchange,提问作者Neenoe
相关产品推荐
相关产品推荐

