简体   繁体   中英

Why doesn't onClick work on custom component in react?

I have two components Star and StarRating (Trying to implement example from book React and Redux , page 135). So I want to render any star and do some actions on click of one star. So, I tried to add console.log in onClick, but it didn't work. Can you help me to fix code and explain why it doesn't work?

StarRating.js

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;

Star.js

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);

.

There is no onClick handler inside of Star component, your should pass handle in ti there:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM