React 中的 OnClick 事件在子组件中不起作用

OnClick event in React not working in child component

我阅读了 "Learning React"(Alex Banks 和 Eve Porcello)并尝试编写一个简单的 Color Organizer 应用程序,这与书中不同。

目前我在StarRating组件中有这样的代码结构

import React from "react";
import Star from "../components/Star";

import { connect } from "react-redux";
import { rateColor } from "../redux/actions";

const StarRating = ({ currentColor, totalStars, rateColor }) => {
  return (
    <div className="star-wrapper">
      <div className="star-rating">
        {[...Array(totalStars)].map((key, i) => {
          return (
            <Star
              key={i}
              selected={i < currentColor.rating}
              onClick={() => rateColor(currentColor.id, i + 1)}
            />
          );
        })}
      </div>
      <div className="star-stats">
        {currentColor.rating} of {totalStars}
      </div>
    </div>
  );
};

const mapDispatchToProps = dispatch => {
  return {
    rateColor: (id, rating) => dispatch(rateColor(id, rating))
  };
};

export default connect(
  null,
  mapDispatchToProps
)(StarRating);

添加和删除减速器工作正常但速率减速器不工作。我需要在单击星号时更改所选星星的值...但什么也没有发生。

一个"colors"减速器:

case RATE_COLOR:
      return {
        colors: [...state.colors.map(c => color(c, action))]
      };

和"color"减速器:

case RATE_COLOR:
      return state.id !== action.payload.id
        ? state
        : { ...state, rating: action.payload.rating };

此处提供所有代码 - https://codesandbox.io/s/color-organizer-react-62ubu?file=/redux/reducers/color.js

您的 Star 组件没有 onClick。确保将点击处理程序从 StarRating 组件传递到 Star 组件。

Working demo

星级评分组件

<div className="star-rating">
        {[...Array(totalStars)].map((key, i) => {
          return (
            <Star
              key={i}
              selected={i < currentColor.rating}
              // onClick={() => rateColor(currentColor.id, i + 1)} // remove this
              rateStarClick={() => rateColor(currentColor.id, i + 1)}
            />
          );
        })}

星级分量

const Star = ({ selected = false, rateStarClick }) => {
  return (
    <div
      onClick={rateStarClick}
      className={selected ? "star selected" : "star"}
    />
  );
};