反应像按钮一样切换 [英] React toggle like button
本文介绍了反应像按钮一样切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个组件,其状态为:{likes:123} 我在喜欢"按钮旁边显示喜欢的次数. 我如何实现此按钮的功能,所以当我单击一次它时,它会添加到点赞(so state.likes = 124),然后如果我想第二次单击它,它将返回到之前的状态(state.likes) = 123).当然,它始终显示正确的点赞次数.这是到目前为止我得到的:
I have a component with a state: {likes: 123} I display the number of likes next to a 'like' button. How do I implement a functionality to this button, so when I click it once, it adds to likes (so state.likes = 124), then if I want to click it a second time it goes back to previous state (state.likes = 123). Of course, it displays the correct number of likes at all times. Here's what I've got so far:
class ProfileInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
likes: this.props.likes,
};
}
handleLike = () => {
this.setState(prevState => ({
likes: prevState.likes + 1,
}));
}
render() {
return (
<div>
<button className="like-button" onClick={this.handleLike}>
Like
</button>
</div>
);
}
}
export default ProfileInfo;
它只会不断添加喜欢.
推荐答案
您可以执行以下操作.
import React from 'react';
class Likes extends React.Component {
constructor(props){
super(props);
this.state = {
likes: 124,
updated: false
};
}
updateLikes = () => {
if(!this.state.updated) {
this.setState((prevState, props) => {
return {
likes: prevState.likes + 1,
updated: true
};
});
} else {
this.setState((prevState, props) => {
return {
likes: prevState.likes - 1,
updated: false
};
});
}
}
render(){
return(
<div>
<p onClick={this.updateLikes}>Like</p>
<p>{this.state.likes}</p>
</div>
);
}
}
export default Likes;
这篇关于反应像按钮一样切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文