开发密码输入框时出现JSX Expressions Must Have One Parent Element错误如何解决
你的代码存在两处核心语法问题,会触发控制台报错:
- 问题1:JSX 不支持返回多个并列的顶层元素
React 要求组件return语句返回的JSX必须有唯一的根节点,你现在直接返回了两个平级的
<div>标签,触发语法报错。可以用空标签<></>(React.Fragment的简写)包裹所有内容,不会额外生成多余的DOM节点。
- 问题2:React 中DOM属性命名和原生HTML有差异
原生的
class属性在JSX中要写成className,原生label标签的for属性要写成htmlFor,否则属性不会生效还会抛出运行时警告。
修正后的完整代码如下:
function HomePage() { return ( <> <div> <p className="text-center text-green-600">Welcome to Next.js a!</p> </div> <div className=" relative "> <label htmlFor="with-indications" className="text-gray-700"> Password <span className="text-red-500 required-dot"> * </span> </label> <input type="text" id="with-indications" className=" rounded-lg border-transparent flex-1 appearance-none border border-gray-300 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-purple-600 focus:border-transparent" name="passwor" placeholder="Password" /> <div className="grid w-full h-1 grid-cols-12 gap-4 mt-3"> <div className="h-full col-span-3 bg-green-500 rounded"> </div> <div className="h-full col-span-3 bg-green-500 rounded"> </div> <div className="h-full col-span-3 bg-green-500 rounded"> </div> <div className="h-full col-span-3 bg-gray-200 rounded dark:bg-dark-1"> </div> </div> <div className="mt-2 text-green-500"> Valid password </div> </div> </> ) } export default HomePage
内容的提问来源于stack exchange,提问作者xCo_re
相关产品推荐
相关产品推荐

