簡體   English   中英

如何使用 Emotion 更改 react-bootstrap 開關(Forms 組件的一部分)的背景顏色

[英]How to change the background color of react-bootstrap's switch (part of the Forms component) using Emotion

如何使用 Emotion 更新在 react-bootstrap(不是 react-bootstrap-switch)中找到的開關的默認藍色背景顏色?

當我 go 進入 Chrome 的開發工具時,我能夠進行更改,但似乎無法在 React 端正確完成。

來自開發者工具

在此處輸入圖像描述 在此處輸入圖像描述

我的嘗試

<Form>
  <Form.Switch
    id="custom-switch"
    label="text goes here"
    bsCustomPrefix={`custom-control-input:checked~custom-control-label::before ${css`background: red;`}`}
  />
</Form>

我也試過使用className代替bsCustomPrefix

實際發生了什么

在此處輸入圖像描述

整個項目都被改變了。

我手頭有類似的任務。 所以我設法通過屬性選擇器實現了這一壯舉(從他們的實現中得到了一個提示)。 所以在樣式表中我寫了這個,

[class='custom-control-input']:checked ~ [class='custom-control-label']::before {
       
        background-color: hotpink; //Example Code

}

在我的 index.css 中,我添加了一個 boostrap 覆蓋部分。 您可以給開關一個特定的 class 或覆蓋所有這些(我覆蓋了所有這些,因為它是為了淺色/深色變化)

.form-check-input {
  background-image: url("data:image/svg+xml,<svg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27><circle r=%273%27 fill=%27%23666%27/></svg>") !important;
}
.form-check-input:checked {
  background-color: #666 !important;
  border-color: #6668 !important;
  background-image: url("data:image/svg+xml,<svg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27><circle r=%273%27 fill=%27%23fff%27/></svg>") !important;
}

.form-check-input:focus {
  border-color: #6668 !important;
  outline: 0;
  box-shadow: none !important;
}

由於沒有代碼示例,因此很難確定,您是否嘗試過這樣的事情:

import styled from '@emotion/styled';

<Form>
  <CustomSwitch
    id="custom-switch"
    label="text goes here"
    bsCustomPrefix={`custom-control-input:checked~custom-control-label::before`}
  />
</Form>

const CustomSwitch = styled(Form.Switch)`
  &::before {
    background: red
  }
`

CSS :

.custom-control-label::before {
    background-color: #28a745;
}

.custom-switch .custom-control-label::after {
    background-color: white;
}

.custom-control-input:checked~.custom-control-label::before {
    background-color: red;
}

為了 :

  function Toggle(props) {
    const [show, setShow] = useState(true);
    return (
        <Form.Check
            onClick={() => setShow(!show)}
            type="switch"
            id="custom-switch"
            label={show ? 'Text1' : 'Text2'}
        />
    );
   }

在此處輸入圖片說明

在此處輸入圖片說明

離開 Pranay Nailwal ......但更簡單的事情。

假設已經安裝了必要的文件來支持交換機。 npm i react-bootstrap@2.0.0 bootstrap@5.1.3

import Form from "react-bootstrap/Form"
...
<Form.Switch id="mySwitch"/>
...

css文件

#mySwitch{
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
  background-color: #28a745;
}
#mySwitch:checked{
  background-color: red;
}

如果您希望按鈕中的 SVG 節點為白色,則需要更新圖像屬性。 在“未選中”時,svg react-botostrap 使用是透明的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM