【问题标题】:How to change a button using Redux如何使用 Redux 更改按钮
【发布时间】:2021-02-11 20:49:30
【问题描述】:

我需要你的帮助。 我有一个任务,创建两个按钮(这些按钮最初是白色背景)。 当我单击其中一个时,我需要两个按钮来更改颜色,使用 Redux。 我创建的按钮。我不知道如何改变颜色。 任何人都可以帮忙吗?我真的很感激。

这是我的代码

import { COUNTER_GREEN, COUNTER_RED } from "../constants";

export const actionRed = () => ({

    type: COUNTER_RED

});

export const actionGreen = () => ({

    type: COUNTER_GREEN

});
=========================
import React from "react";
import { connect } from "react-redux";

import { actionGreen, actionRed } from "../../actions/counter";

const Counter = ({ actionRed, actionGreen }) => {
    return (
        <div>
            <button onClick={actionRed}>Red</button>

            <button onClick={actionGreen}>Green</button>
        </div>
    );
}

const mapStateToProps = () => ({});

const mapDispatchToProps = {
    actionRed,
    actionGreen
};

export const CounterContainer = connect(mapStateToProps,mapDispatchToProps)(Counter);
======================


const red = 'red';
const green = 'green';

const redtest = {
color: 'red'
}


export const counterReducer = (state={redtest}, action) => {
    switch(action.type) {
        case "COUNTER_RED": {
            return {
                state: {redtest}
            };

        }
        case "COUNTER_GREEN": {
            return {
                state:green


            };
        }
        default: {
            return state;
        }
    }
};


【问题讨论】:

  • 所以,我看到了一些东西。你的状态不一致。 {redtest}green。您可以使用 mapStateToProps 更改颜色,使其看起来更像,但您需要修复您的状态。

标签: reactjs redux


【解决方案1】:

在你的 redux 存储中创建一个 buttonColor 变量。导入与组件中的道具相同的变量,为按钮提供背景。在按钮单击时调度一个将更改按钮颜色的事件。

如果您没有在应用程序的其他任何地方使用此颜色属性,我建议您将其移至组件状态而不是 redux 存储。如果您使用的是功能组件,您可以使用钩子来更新状态。

【讨论】:

  • 怎么办?我不明白。我在谷歌搜索但找不到答案
【解决方案2】:

如果您想继续使用功能组件,请使用如下钩子。

import React from "react";
import { connect } from "react-redux";

const Counter = () => {

    const [btnColor, changeBtnColor] = useState('blue');
    return (
        <div>
            <button onClick={()=>changeBtnColor('red')} style={{backgroundColor: btnColor}}>Red</button>

            <button onClick={()=>changeBtnColor('green')} style={{backgroundColor: btnColor}}>Green</button>
        </div>
    );
}

export default Counter;

如果你想切换到基于类的组件,试试下面的 sn-p。

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      btnColor: 'blue'
    };
  }

  render() {
    return (
      <div>
            <button onClick={()=>this.setState({this.state.btnColor: 'red'})} style={{backgroundColor: this.state.btnColor}}>Red</button>

            <button onClick={()=>this.setState({this.state.btnColor: 'green'})} style={{backgroundColor: this.state.btnColor}}>Green</button>
      </div>
    );
  }
}

【讨论】:

  • 不使用钩子可以吗?
  • 当然。第二个 sn-p 没有反应钩子。
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2019-10-23
  • 1970-01-01
  • 2011-10-25
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多