为什么此代码打印 'undefined' 而不是 StarRating 组件?

Why does this code print 'undefined' instead of a StarRating Component?

import React, { Component } from "react";
import Star from "./Star";

class StarRating extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rating: 0,
      stars: this.returnStars(),
    };
    this.getStars = this.getStars.bind(this);
  }
  getStars() {
    console.log(this);
  }
  returnStars() {
    const stars = [];
    for (let i = 0; i < 5; i++) {
      const star = <Star handleStar={this.getStars} />;
      stars.push(star);
    }
    return stars;
  }

  render() {
    return <ul className="course--stars">{this.state.stars}</ul>;
  }
}

export default StarRating;

// This is Star component
import React from "react";

const Star = (props) => {
  return (
    <li onClick={props.handleStar}>
      <svg x="0px" y="0px" viewBox="0 0 16 15" className="star">
        <path
          d="M8.5,0.3l2,4.1c0.1,0.2,0.2,0.3,0.4,0.3l4.6,0.7c0.4,0.1,0.6,0.6,0.3,0.9l-3.3,3.2c-0.1,0.1-0.2,0.3-0.2,0.5l0.8,4.5
      c0.1,0.4-0.4,0.8-0.8,0.6l-4.1-2.1c-0.2-0.1-0.3-0.1-0.5,0l-4.1,2.1c-0.4,0.2-0.9-0.1-0.8-0.6l0.8-4.5c0-0.2,0-0.4-0.2-0.5L0.2,6.2
      C-0.2,5.9,0,5.4,0.5,5.3L5,4.7c0.2,0,0.3-0.1,0.4-0.3l2-4.1C7.7-0.1,8.3-0.1,8.5,0.3z"
        />
      </svg>
    </li>
  );
};

export default Star;
当在 Star 组件上调用 onClick 函数时,getStars() 记录未定义而不是 StarRating class??

当我使用此语法呈现 Star 组件时,它可以正常工作并记录 StarRating

render() {
    return <ul className="course--stars">{this.returnStars()}</ul>;
  }

我不知道我做错了什么。

我刚刚看了你的代码,我想这就是原因。在绑定 returnStars() 函数之前设置 stars 状态变量的值。尝试声明状态变量时,首先将初始值设置为[]并在组件挂载上设置。

为避免这种情况,请尝试在 componentDidMount 上设置 stars,然后在挂载之前绑定 returnStars,它将起作用。

componentDidMount() {
    this.setState({stars: this.returnStars()})
}

希望这能帮助你理解!