scale(1)
我希望能够单击为LeagueBadge组件的图像,并在其同级LeagueInfo中增加amountOfPlayers的值。我已经在Google上反应了兄弟姐妹之间的交流,并且只找到了带有输入标签和onChange的示例,但是在这里我想要img标签或按钮和onClick。
答案 0 :(得分:2)
您可以将amountOfPlayers
的状态提升到<Leauge />
组件中,以便:
-可以从<LeagueBadge />
触发更新
-并且该状态可以传递到您的<LeagueInfo />
组件
这将允许您根据需要在<LeagueInfo />
和<LeagueBadge />
兄弟姐妹之间共享和同步状态。
为此,您需要向onClick
添加一个<LeagueBadge />
回调,该回调在单击img
元素时触发。在<Leauge />
渲染方法中,您可以提供增加amountOfPlayers
中<Leauge />
状态的逻辑。当amountOfPlayers
递增并调用setState
(在<Leauge />
中)时,这又将导致您的<Leauge />
组件重新呈现自身(以及子级/同级) 。由于amountOfPlayers
的更新值是作为道具传递给<LeagueInfo />
组件的,因此此更新后的值将在<LeagueInfo />
中呈现,从而有效地满足您的需求。
类似的方法可能对您有用:
class LeagueBadge extends Component {
render() {
// Add props.onClick callback to trigger click event in <League />
// component
return (
<img src={this.props.badgeUrl} alt="missing alt text"
onClick={() => this.props.onClick()} />
);
}
}
class LeagueInfo extends Component {
constructor(props) {
super(props);
this.state = {
// amountOfPlayers: null, // This is not needed, as it's supplied by props
rpPerSecond: null,
rpCost: null,
};
}
render() {
return (
<div>
<h4>{this.props.name} players: {this.props.amountOfPlayers}</h4>
<h4>RP per second: {this.props.rpPerSecond}</h4>
<h4>RP cost: {this.props.rpCost}</h4>
</div>
);
}
}
class League extends Component {
componentWillMount() {
this.setState({
amountOfPlayers : 0
})
}
render() {
// Locally defined function that increments amountOfPlayers and
// updates state
const incrementAmountOfPlayers = () => {
this.setState({ amountOfPlayers :
this.state.amountOfPlayers + 1 })
}
return (
<div>
<LeagueBadge badgeUrl={this.props.badge}
onClick={ () => incrementAmountOfPlayers() } />
<LeagueInfo name={this.props.name} amountOfPlayers={ this.state.amountOfPlayers } />
</div>
);
}
}
答案 1 :(得分:2)
将您的状态保留在League组件中,并传递负责将其更改为LeagueBadge的功能,如下所示:
class League extends Component {
constructor(props) {
super(props);
this.state = {
amountOfPlayers: null,
};
}
handleClick = () => {
this.setState(prevState => {
return {amountOfPlayers: prevState.amountOfPlayers + 1}
})
}
render() {
return (
<div>
<LeagueBadge badgeUrl={this.props.badge} incrementPlayers={this.handleClick}/>
<LeagueInfo name={this.props.name} amountOfPlayers={this.state.amountOfPlayers}/>
</div>
);
}
}
function LeagueBadge(props) {
return (
<img src={props.badgeUrl} alt="missing alt text" onClick={this.props.incrementPlayers}/>
);
}
在您的信息组件中使用this.props.amountOfPlayers
。