为什么没有在on响应自定义组件上工作?

时间:2018-04-15 13:41:58

标签: javascript reactjs

我有两个组件Star和StarRating。(尝试从书React和Redux第135页实现示例),所以我想渲染任何一个星并在点击一个星时做一些动作,所以StarRating的代码:

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

class StarRating extends Component {
  displayName: "star-rating";

  constructor(props) {
    super(props);
    this.state = {
      totalStars: 5,
      starsSelected: 2
    };
    this.change = this.change.bind(this);
  }

  change(starsSelected) {
    console.log(starsSelected);
    this.setState({ starsSelected });
  }

  render() {
    const  totalStars  = 5;
    const { starsSelected } = this.state;
    console.log({ totalStars });
    return (
      <div className="star-rating">
        {[...Array(totalStars)].map((n, i) => {
          return (
            <Star
              key={i}
              selected={i < starsSelected}
              onClick={() => this.change(i + 1)}
            />
          );
        })}
      </div>
    );
  }
}

export default StarRating;

并且有代码:

import React from "react";
import { withStyles } from "material-ui-next";

const styles = {
  star: {
    cursor: "pointer",
    height: 25,
    width: 25,
    margin: 2,
    float: "left",
    backgroundColor: "grey",
    clipPath: `polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);`
  },
  selected: {
    cursor: "pointer",
    height: 25,
    width: 25,
    margin: 2,
    float: "left",
    backgroundColor: "green",
    clipPath: `polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);`
  }
};

const Star = ({ selected = true, classes }) => {
  return <div className={selected ? classes.selected : classes.star} />;
};

export default withStyles(styles)(Star);

所以,我尝试在onClick中添加console.log,但它也没有调用。 你能帮助我修改代码以及它为什么不起作用吗?

1 个答案:

答案 0 :(得分:5)

Star组件中没有onClick处理程序,你应该在那里传递句柄:

const Star = ({ selected = true, classes, onClick }) => {
  return <div onClick={onClick} className={selected ? classes.selected : classes.star} />;
};