class StarRating extends Component {
constructor (props) {
super(props)
}
log = (selected) => {
console.log(selected)
}
render() {
return <div>
<Star
selected = {true}
doClick={() => this.log(this.selected)}
/>
<Star />
<Star/>
<Star/>
<Star/>
</div>
}
}
我需要传递“ selected”(在我的情况下为“ true”)才能登录,但是它写为“ undefined”,我应该更改什么?
这是Star组件。
const Star = ({selected, doClick=f=>f}) =>
<div className = {(selected) ? "star selected" : "star"} onClick={doClick}></div>
Star.propTypes = {
selected: PropTypes.bool,
doClick: PropTypes.func
}
export default Star
答案 0 :(得分:1)
您需要像下面那样构造StarRating组件
class StarRating extends Component {
constructor (props) {
super(props);
this.state = {
selected: false
}
}
log = () => {
this.setState({
selected: true
});
}
render() {
return <div>
<Star
selected = {this.state.selected}
doClick={this.log}
/>
<Star />
<Star/>
<Star/>
<Star/>
</div>
}
}
和
const Star = ({selected, doClick}) => <div className = {(selected) ? "star selected" : "star"} onClick={doClick}></div>
Star.propTypes = {
selected: PropTypes.bool,
doClick: PropTypes.func
}
export default Star;