繁体   English   中英

如何在单击时更改 Base Web Button 组件的 styles?

[英]How to change the styles of Base Web Button component on click?

我想在使用 React 单击按钮时更改 Base Web Button 组件的颜色和背景颜色。 如何更改按钮单击时按钮的 styles?

我尝试使用$isSelected属性来检测点击,但这对我没有帮助。 这是代码:

import { Button } from 'baseui/button'

...

<Button
  kind="secondary"
  size="compact"
  shape="pill"
  overrides={{
    BaseButton: {
      style: ({ $isSelected }) => ({
        color: $isSelected ? 'white' : 'black',
        backgroundColor: $isSelected ? 'black' : 'white',
      }),
    },
  }}
>
  Hello
</Button>

我该如何处理?

您可以创建包含真值或假值的 state,然后根据按钮是否被单击来设置按钮样式。

import * as React from "react";
import { Button } from "baseui/button";

export default () => {
  const [clicked, setClicked] = React.useState(false);
  return (
    <Button
      kind="secondary"
      size="compact"
      shape="pill"
      overrides={{
        BaseButton: {
          style: () => ({
            color: clicked ? "white" : "black",
            backgroundColor: clicked ? "black" : "white",
          }),
        },
      }}
      onClick={() => setClicked(!clicked)}
    >
      Hello
    </Button>
  );
};

代码沙盒: https://codesandbox.io/s/base-web-button-forked-gvxi2v?file=/src/example.js:513-523

示例直接从https://baseweb.design/components/button 派生

如果你想创建许多这样的按钮,你可以将示例提取到它自己的组件中,并根据需要多次渲染它们,它们每个都会有自己的点击 state。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM