首页 > 解决方案 > 函数被声明但它的值从未被读取: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>

标签: javascriptreactjs

解决方案


改名:

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) {}


推荐阅读