React组件未生效求助:已声明组件提示未使用
React组件不渲染?问题出在组件命名上!
嘿,别担心,新手遇到这种小问题太正常啦!我帮你看看哪里出问题了~
你遇到的核心问题是React组件的命名规则:React要求自定义组件的名称必须以大写字母开头!你写的commentText和commentDate是小写开头,React会把它们当成普通的HTML标签(比如<div>、<p>这种)来处理,而不是你定义的自定义组件,所以VS Code会提示“已声明但未使用”,页面上自然也不会渲染这两部分内容。
修改后的代码
只需要把组件名改成大写开头,同时在调用组件的地方也对应修改成大写标签就可以了:
JavaScript部分
function formatDate(date) { return date.toLocaleDateString(); } function Avatar(props) { return ( <img className="Avatar" src={props.user.avatarUrl} alt={props.user.name}/> ); } function UserInfo(props){ return ( <div className="UserInfo"> <Avatar user={props.person} /> <div className="UserInfo-Name"> {props.person.name} </div> </div> ); } // 组件名改为大写开头 function CommentText(props){ return ( <div className="Comment-text"> {props.sentence} </div> ); } // 组件名改为大写开头 function CommentDate(props){ return( <div className="Comment-date"> {formatDate(props.dates)} </div> ); } function Comment(props) { return ( <div className="Comment"> <UserInfo person={props.author}/> {/* 调用时也使用大写标签 */} <CommentText sentence={props.text} /> <CommentDate dates={props.date} /> </div> ); } const comment = { date: new Date(), text: 'I hope you enjoy learning React!', author: { name: 'Hello Kitty', avatarUrl: 'https://placekitten.com/g/64/64', }, }; ReactDOM.render( <Comment date={comment.date} text={comment.text} author={comment.author} />, document.getElementById('root') );
HTML部分(这部分不需要修改)
<html> <head> <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> </head> <body> <div id="root"></div> </body> </html>
为什么要这样?
React通过首字母的大小写来区分内置HTML元素和自定义组件:
- 小写开头的标签(比如
<div>、<p>)会被React解析为原生HTML元素 - 大写开头的标签(比如
<UserInfo>、<CommentText>)才会被识别为你定义的自定义组件,从而正常渲染组件内容
这样修改之后,你的<CommentText>和<CommentDate>组件就能正常工作啦😉
内容的提问来源于stack exchange,提问作者Suraj Chaudhary
相关产品推荐
相关产品推荐

