简体   繁体   中英

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

I want to change the color and background color of the Base Web Button component on button click using React. How can I change the styles of the button on button click?

I tried to use $isSelected prop to detect clicking, but this didn't help me. Here is the code:

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>

How can I handle it?

You could create state that holds a true or false value and then style the button according to whether or not it has been clicked.

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>
  );
};

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

Example forked directly from https://baseweb.design/components/button

If you wanted to create many of these buttons, you could extract the example into it's own component and render them out as many times as you want and they will each have their own clicked state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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