javascript - 使用 React 的具有 3 个状态的按钮

标签 javascript css reactjs

我需要一个具有 3 种状态的按钮。

每个状态都需要处理点击并发送一个值。

用例是:

  • 不喜欢
  • 收藏
  • super 喜欢

我尝试使用 this.state.count + 1 来指示级别,但没有成功。我不确定这也是最好的方法。

我使用 const fill 作为 CSS 值(颜色),我将传递给 svg 元素。

这是我的尝试,但它受到限制,因为 checked 只有 2 个状态(开/关),我需要 3 个。它也在 this codepen 中.

class Switch extends React.Component {
  constructor ( props ) {
    super( props );
    this.state = {
      checked: !!props.checked
    };
  }
  handleClick(e) {
        this.setState({
      checked: !this.state.checked
    });
  }

  render () {
    const fill = this.state.checked ? "#E1E0DD" : "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

const App = () => (
    <div>
        <Switch checked={ true } />
    </div>
)

React.render( <App />, document.getElementById( "page" ) );

最佳答案

您的代码存在多个问题。

首先,不要从其 props 派生组件的状态 - 这是一种反模式。

其次,因为 React 可以批处理 setState 调用,所以你应该使用 function(prevState, nextProps)当您将新状态基于先前状态时,setState 的参数而不是对象。

第三,如上面的评论所述,您永远无法通过使用 bool 值获得三种状态。

我会像这样实现它:

class TripleSwitch extends React.Component {
  constructor() {
    super();
    this.state = {
       favourite: 0
    }
  }

  handleClick() {
    this.setState((prevState) => ({
       favourite: (prevState.favourite + 1) % 3
    }));
  }

  render () {
    const { favourite } = this.state;
    const fill = favourite === 0 ? "#E1E0DD" :
                 favourite === 1 ? "#000444" : 
                 "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

关于javascript - 使用 React 的具有 3 个状态的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082797/

相关文章:

javascript - 我想连接 react 和 firebase

reactjs - 在 React 测试库中测试点击事件

javascript - velocity-react - 在组件更新后动画 scrollTop

javascript - 在javascript中将朱利安日期数字转换为正常日期(utc)

javascript - 将元素符号控件添加到选项卡式幻灯片

css - ReactJS 无法识别小屏幕上的触摸/点击

javascript - 这次脊椎出了什么问题吗?

javascript - 如何从 React 类外部更改 Modal 状态?

css - 在 Bootstrap 中设置列​​表框宽度以填充列宽度

html - 为什么 flex 元素不缩小过去的内容大小?