javascript - 函数被声明但它的值从未被读取:React
问题描述
我是 Reactjs 的新手,如果这很蹩脚,请原谅我。我正在关注 Reactjs 文档来学习 React 以及在组件和 props中自我实现练习。我遇到了以下奇怪的行为: 在“评论”功能中,<UserInfo ../> 标签工作正常,但 <commentText ../> 和 <commentDate ../> 不起作用,对于它们各自的功能,VScode 说他们已声明,但从未使用过它们的值。
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>
<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>
解决方案
改名:
function commentText(props){
到
function CommentText(props){
和:
function commentDate(props) {
到
function CommentDate(props) {
然后:
<div className="Comment">
<UserInfo person={props.author}/>
<CommentText sentence={props.text} />
<CommentDate dates={props.date} />
</div>
React 组件与常规函数不同,它们的首字母必须大写。将反应组件构造为:
const CommentDate = (props) => {}
代替
function CommentDate(props) {}
推荐阅读
- python - 为什么 scapy 模块不一致,在嗅探期间丢失恒定数量的数据包?
- android - 如何阻止方法被调用两次?
- pca - 如何使用 SVD 和 RANSAC 在某些图像像素上拟合 3D 平面 Pi?
- linux - su 在脚本中将其重定向到超级用户目录
- unity3d - UnityWebRequestAssetBundle 加载assetbundle 为空
- ios - fontDescriptorWithSymbolicTraits 方法返回不同字体系列中的新字体描述符引用,而不是 iOS13 上的相同字体系列
- php - 是否可以在 symfony 项目目录之外编写独白日志?
- java - springframework 版本 5.0.5.RELEASE 引起:java.lang.NoClassDefFoundError: org/springframework/core/task/AsyncListenableTaskExecutor
- c# - 如何解决 Visual Studio Code 中未使用的代码错误?
- c# - 如何在 .NetCore 中使用 Selenium C# 记录测试执行