[英]Why doesn't onClick work on custom component in react?
我有两个组件Star
和StarRating
(尝试实现React和Redux书中的示例,第135页)。 因此,我想渲染任何星星并在单击一颗星星时执行一些操作。 因此,我尝试在onClick中添加console.log
,但是没有用。 您能帮我修复代码并解释为什么它不起作用吗?
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);
。
Star
组件内部没有onClick处理程序,您应该在其中传递句柄:
const Star = ({ selected = true, classes, onClick }) => {
return <div onClick={onClick} className={selected ? classes.selected : classes.star} />;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.