css - 如何创建自定义单选按钮?

标签 css reactjs sass radio-button

我一直在网上寻找创建自定义复选框和单选按钮的方法。我已经设法创建了一个复选框,但我遇到的问题是单选框单击它不会激活或触发对我的输入的 onChange 调用。我目前有这个:

const customButtons = props => {
 const [isChecked, setChecked] = React.useState(false);

 const toggleCheck = e => {
  setChecked(e.target.checked || !isChecked)
 }

 return (
  <>
   <span className={container}>
    <input type={props.type} checked={isChecked} onChange={e => toggleCheck(e)} id={props.id} />
    <span></span>
   </span>
  </>
 ) 
}

我已经使用 css 获取覆盖单选按钮的跨度并制作了原始单选按钮 display: none;但是当我点击跨圈时,它不会触发点击。我在跨度中添加了一个 onClick:<span onClick={toggleCheck}>但这会导致单击两次时取消选中单选按钮。在保持原始行为的同时实现自定义单选按钮的更好方法是什么?

如果重要的话,我也在使用 scss。

最佳答案

如果输入未设置为 display: none,您的方法适用于 radiocheckboxes,当然就像正常输入一样。但是,如果您将它们设置为显示:无,则实际上是将它们隐藏在 UI 事件之外,因此它们根本不会触发任何点击。


TLDR: Better approach would be, set the opacity: 0 on the input, use a label with htmlFor to trigger the change. Then style the label pseudo elements to look like radios.

这里是一个链接 Live Code Sandbox这里


由于您没有提供样式,因此很难说出您是如何在视觉上布置您的自定义输入的。用我的方法,

  • 大多数用户界面在只需要一个选项进行选择时使用radios,而在多个选择时使用checkboxes。也就是说,很容易将状态从单个单选选项提升到父单选组组件,然后传递单选状态,同时让复选框控制它们各自的状态,因为它们被构建为彼此独立。

  • 另一个观察结果是,您的 radio 缺少 name 属性(为什么您看到多次点击而变化很少或根本没有变化的原因)使它们脱节从彼此。要将它们放在一个组中,它们需要共享一个共同的 name 属性,这样您就可以只针对每个 radio 的选项值。

  • 一旦选择了没有公共(public)组(无名称属性)的所有单选选项,您就无法在 UI 上取消选择它们,因此它们不会触发任何进一步的 onChange 事件。出于这个原因,如果不是强制性的,建议添加一个重置选项以清除选项。

这是每个 radio 输入组件的代码。

const RadioInput = ({ name, label, value, isChecked, handleChange }) => {
  const handleRadioChange = e => {
    const { id } = e.currentTarget;
    handleChange(id); // Send back id to radio group for comparison
  };

  return (
    <div>
      {/* Target this input: opacity 0 */}
      <input
        type="radio"
        className="custom-radio"
        name={name}
        id={value} // htlmlFor targets this id.
        checked={isChecked}
        onChange={handleRadioChange}
      />
      <label htmlFor={value}>
        <span>{label}</span>
      </label>
    </div>
  );
};

看,通常在编写自定义输入来覆盖原生输入时,如果您以 label 元素为目标并利用其 for a.k.a htmlFor 会更容易> 属性来选择输入。从以前的努力来看,很难用自定义元素取悦所有屏幕阅读器,尤其是当您覆盖的 native input 设置为不显示时。

在我看来,最好将其绝对定位,将其不透明度设置为零,然后让标签触发它的变化。

链接到 Sandbox here


组件的完整代码

App.js



import React, { useState } from "react";
import "./styles.scss";

/*
Let Checkbox the controls its own state.
Styling 'custom-radio', but only make the borders square in .scss file.
*/
const CheckboxInput = ({ name, label }) => {
  const [isChecked, setIsChecked] = useState(false);

  const toggleCheck = e => {
    setIsChecked(() => !isChecked);
  };

  return (
    <div>
      <input
        type="checkbox"
        className="custom-radio"
        name={name}
        id={name}
        checked={isChecked}
        onChange={toggleCheck}
      />
      <label htmlFor={name}>
        <span>{label}</span>
      </label>
    </div>
  );
};

/*
The custom radio input, uses the same styles like the checkbox, and relies on the 
radio group parent for its state.
*/
const RadioInput = ({ name, label, value, isChecked, handleChange }) => {
  const handleRadioChange = e => {
    const { id } = e.currentTarget;
    handleChange(id);
  };

  return (
    <div>
      <input
        type="radio"
        className="custom-radio"
        name={name}
        id={value}
        checked={isChecked}
        onChange={handleRadioChange}
      />
      <label htmlFor={value}>
        <span>{label}</span>
      </label>
    </div>
  );
};

/*
This is what control the radio options. Each radio input has the same name attribute
that way you can have multiple groups on the form.
*/
const RadioGropupInput = () => {
  const [selectedInput, setSelectedInput] = useState("");

  const handleChange = inputValue => {
    setSelectedInput(inputValue);
  };

  return (
    <>
      <div>
        {/*
          You could map these values instead from an array of options
          And an option to clear the selections if they are not mandatory.
          PS: Add aria attributes for accessibility
        */}
        <RadioInput
          name="option"
          value="option-1"
          label="First Choice"
          isChecked={selectedInput === "option-1"}
          handleChange={handleChange}
        />
        <RadioInput
          name="option"
          value="option-2"
          label="Second Choice"
          isChecked={selectedInput === "option-2"}
          handleChange={handleChange}
        />
        <RadioInput
          name="option"
          value="option-3"
          label="Third Choice"
          isChecked={selectedInput === "option-3"}
          handleChange={handleChange}
        />
      </div>
    </>
  );
};

export default () => (
  <div className="App">
    <RadioGropupInput />
    <hr />
    <CheckboxInput name="remember-me" label="Remember Me" />
    <CheckboxInput name="subscribe" label="Subscribe" />
  </div>
);


风格



.custom-radio {
  /* Hide the input element and target the next label that comes after it in the DOM */
  position: absolute;
  display: inline-block;
  opacity: 0;

  & + label {
    cursor: pointer;
    display: inline-block;
    position: relative;
    white-space: nowrap;
    line-height: 1rem;
    margin: 0 0 1.5rem 0;
    padding: 0 0 0 1rem;
    transition: all 0.5s ease-in-out;

    span {
      margin-left: 0.5rem;
    }

    /* Styles these pseudo elements to look like radio inputs. */
    &::before,
    &::after {
      content: '';
      position: absolute;
      color: #f5f5f5;
      text-align: center;
      border-radius: 0;
      top: 0;
      left: 0;
      width: 1rem;
      height: 1rem;
      transition: all 0.5s ease-in-out;
    }

    &::before {
      text-rendering: auto;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      line-height: 1rem;
      border-radius: 0;
      background-color: #ffffff;
      color: #ffffff;
      box-shadow: inset 0 0 0 1px #666565, inset 0 0 0 1rem #ffffff,
        inset 0 0 0 1rem #6b0707;
    }

    &:hover,
    &:focus,
    &:active {
      color: red;
      font-weight: bolder;
      transition: all 0.3s ease;
      outline: none;

      &::before {
        color: #ffffff;
        animation-duration: 0.5s;
        animation-name: changeSizeAnim;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        box-shadow: inset 0 0 0 1px #6b0707, inset 0 0 0 16px #ffffff,
          inset 0 0 0 16px #6b0707;
      }
    }
  }

  &:focus,
  &:hover,
  &:checked {
    & + label {
      color: #220000 !important;
    }

    & + label::before {
      animation-duration: 0.3s;
      animation-name: selectCheckboxAnim;
      animation-iteration-count: 1;
      animation-direction: alternate;
      border: solid 1px rgba(255, 0, 0, 0.5);
      box-shadow: inset 0 0 0 1px #bc88d4, inset 0 0 0 0 #ffffff,
        inset 0 0 1px 2px #6d1717;
    }
  }

  &:checked {
    & + label::before {
      content: '✔'; /* Swap out this emoji checkmark with maybe an icon font of base svg*/
      background-color: #d43333;
      color: #ffffff;
      border: solid 1px rgba(202, 50, 230, 0.5);
      box-shadow: inset 0 0 0 1px #bc88d4, inset 0 0 0 0 #ffffff,
        inset 0 0 0 16px #d43333;
    }
  }

  & + label {
    &::before {
      border-radius: 50%;
    }
  }

  &[type=checkbox] {
    & + label {
      &::before {
        /* Remove the border radius on the checkboxes for a square effect */
        border-radius: 0;
      }
    }
  }


  @keyframes changeSizeAnim {
    from {
      box-shadow: 0 0 0 0 #d43333,
        inset 0 0 0 1px #d43333,
        inset 0 0 0 16px #FFFFFF,
        inset 0 0 0 16px #d43333;
    }

    to {
      box-shadow: 0 0 0 1px #d43333,
        inset 0 0 0 1px #d43333,
        inset 0 0 0 16px #FFFFFF,
        inset 0 0 0 16px #d43333;
    }
  }

  /* Add some animations like a boss, cause why would you hustle to build
  a custom component when you can't touch this!
  */
  @keyframes selectCheckboxAnim {
    0% {
      box-shadow: 0 0 0 0 #bc88d4,
        inset 0 0 0 2px #FFFFFF,
        inset 0 0 0 3px #d43333,
        inset 0 0 0 16px #FFFFFF,
        inset 0 0 0 16px #d43333;
    }

    100% {
      box-shadow: 0 0 20px 8px #eeddee,
        inset 0 0 0 0 white,
        inset 0 0 0 1px #bc88d4,
        inset 0 0 0 0 #FFFFFF,
        inset 0 0 0 16px #d43333;
    }
  }
}

/* Styles used to test out and reproduce out your approach */
.container.control-experiment {
  background: #fee;


  span,
  input {
    display: flex;

    border: solid 1px red;
    width: 2rem;
    height: 2rem;
    line-height: 2rem;
    display: inline-block;
  }

  input {    
    position: absolute;
    margin: 0;
    padding: 0;
  }

  input[type='radio'] {
    // display: none; /* Uncommenting this out makes all your inputs unsable.*/
  }
}

我重复强调一下,不要忘记为自定义输入添加 aria 属性。 您可以再次测试 live Sandbox

关于css - 如何创建自定义单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61901662/

相关文章:

javascript - ReactJS - 使用 Mutation Observer 检测第三方 DOM 插入

javascript - React 中的 setState 函数不会改变我的组件的状态

css - 使用 Gulp 将 Bootstrap-Material Scss 转换为 CSS 时找不到导入

css - 如何使 SCSS linter 接受蛇形小写和带连字符的小写作为选择器命名约定

html - 以 HTML (wordpress) 居中超链接

javascript - Electron 应用程序无法正常工作,控制台显示 'require not defined'

javascript - 类型错误 : Cannot read property 'avatar' of null

html - 始终在动态内容 div 中获得阅读更多链接的相同位置

css - 在 Windows 8 应用程序中拖动内容超过滚动限制时如何禁用反弹?

css - 垫色不透明度的第二个参数是什么?