简体   繁体   English

如何在 React 的 Toggle Switch 组件内添加文本?

[英]How to add text inside a Toggle Switch Component in React?

How can I add text inside a Switch component in ReactJS?如何在 ReactJS 的 Switch 组件内添加文本? I am trying to add EN and PT text inside the Switch Component.我正在尝试在 Switch 组件中添加ENPT文本。

I'm not using any lib, I built the component with only css, because I needed it to have this specific customization, so I found it easier to do with css.我没有使用任何库,我只使用 css 构建了组件,因为我需要它来进行这种特定的定制,所以我发现使用 css 更容易。

I put my project intocodesandbox我把我的项目放入代码沙箱

在此处输入图像描述

 import React from "react"; import "./switch.css"; const Switch = ({ isOn, handleToggle, onColor }) => { return ( <> <input checked={isOn} onChange={handleToggle} className="react-switch-checkbox" id={`react-switch-new`} type="checkbox" /> <label style={{ background: isOn && onColor }} className="react-switch-label" htmlFor={`react-switch-new`} > <span className={`react-switch-button`} /> </label> </> ); }; export default Switch;
 .react-switch-checkbox { height: 0; width: 0; visibility: hidden; }.react-switch-label { display: flex; align-items: center; justify-content: space-between; cursor: pointer; width: 100px; height: 50px; background: #fff; position: relative; transition: background-color 0.2s; }.react-switch-label.react-switch-button { content: ""; position: absolute; top: 2px; left: 2px; width: 45px; height: 45px; transition: 0.2s; background: #000; box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29); }.react-switch-checkbox:checked +.react-switch-label.react-switch-button { left: calc(100% - 2px); transform: translateX(-100%); }.react-switch-label:active.react-switch-button { width: 60px; }

Thank you very much for any help!!非常感谢您的帮助!!

Take a look at my fork of your sandbox.看看我对你的沙箱的 fork First of all, I moved the <input> into the <label> so it doesn't require the id / htmlFor structure that would break due to duplicate id's once you use multiple switches.首先,我将<input>移到<label>中,因此它不需要id / htmlFor结构,一旦使用多个开关,就会由于重复的 id 而中断。

The text span s are now in their own div inside the label .文本span现在位于label内自己的div中。 They each have 50% width, are aligned to the left and right edges respectively and use flexbox to center their contents.它们各有 50% 的宽度,分别与左右边缘对齐,并使用 flexbox 将其内容居中。

Depending on the width of the white area in either state of the checkbox, you might want to change the spans' width to center the text correctly.根据复选框的 state 中白色区域的宽度,您可能希望更改跨度的宽度以正确居中文本。 Also, the label texts can be moved to a property for reusability.此外,可以将 label 文本移动到属性以实现可重用性。

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

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