像按钮一样反应切换

React toggle like button(像按钮一样反应切换)

本文介绍了像按钮一样反应切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个状态为:{likes: 123} 的组件我在喜欢"按钮旁边显示喜欢的数量.我如何为这个按钮实现一个功能,所以当我单击它一次时,它会添加到喜欢(所以 state.likes = 124),然后如果我想第二次单击它,它会返回到以前的状态(state.likes= 123).当然,它始终显示正确的点赞数.到目前为止,这是我所得到的:

class ProfileInfo extends React.Component {构造函数(道具){超级(道具);这个.state = {喜欢:this.props.likes,};}句柄 = () =>{this.setState(prevState => ({喜欢:prevState.likes + 1,}));}使成为() {返回 (

<button className="like-button" onClick={this.handleLike}>喜欢</按钮></div>);}}导出默认 ProfileInfo;

它只是不断地添加喜欢.

解决方案

您可以执行以下操作.

这里是一个codesandbox,其中包含更完整的代码版本.

从'react'导入反应;类喜欢扩展 React.Component {构造函数(道具){超级(道具);这个.state = {喜欢:124,更新:假};}更新喜欢 = () =>{如果(!this.state.updated){this.setState((prevState, props) => {返回 {喜欢:prevState.likes + 1,更新:真};});} 别的 {this.setState((prevState, props) => {返回 {喜欢:prevState.likes - 1,更新:假};});}}使成为(){返回(

<p onClick={this.updateLikes}>点赞</p><p>{this.state.likes}</p></div>);}}导出默认点赞;

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;

It just adds likes on and on.

解决方案

You could do something like the following.

Here is a codesandbox with a more complete version of the code.

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;

这篇关于像按钮一样反应切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:像按钮一样反应切换

基础教程推荐