首页 > 解决方案 > 尝试自定义我的单选按钮,但什么都不会改变

问题描述

我想将选中的按钮更改为不同的颜色。我没有checked属性,因为我通过对象映射以显示值。我已经尝试定位输入标签,但似乎没有任何效果。我也希望能够在悬停时改变颜色,但我也没有运气。

这是我的CSS:

.radio-btn {
    margin: 0 10px 10px 0;
    background-color: black;
}

.radio-btn:hover {
    background-color: black;
}

这是按钮文件:

import React from "react";

const EyewearPurchaseBtn = (props) => (
    <div>
        <form className="eyewear-purchase-form" onSubmit={props.handleSubmit}>
            <h3>Select Size</h3>

                    {
                        props.sizes.map( size => (
                            <div key={size} >
                            <input onChange={props.handleChange} className="radio-btn" type="radio" name="purchaseVal" value={size} />
                            <label className="eyewear-purchase-label">{size}</label><br/>   
                            </div>
                        ))
                    }

                    <button className="buy-now">Buy Now</button>    
                </form>
    </div>
);

export default EyewearPurchaseBtn;

标签: cssreactjs

解决方案


我不知道它是否正是您正在寻找的,但您可以使用 css 创建假单选按钮。这是一个例子:

input[type="radio"] {
  opacity: 0;
  z-index: 1;
}

label { position: relative; }

label:before, label:after {
  content: "";
  position: absolute;
  border-radius: 50%;
  top: 50%;
  transform: translateY(-50%);
  z-index: -1;
}

label:before {
  width: 15px;
  height: 15px;
  background-color: #3b3a39;
  left: -20px;
}

label:after {
  width: 7px;
  height: 7px;
  background-color: #f0e9e9;
  left: -16px;
  opacity: 0;
}

input[type="radio"]:checked + label:after { opacity: 1; }
input[type="radio"]:hover + label:before { background-color: #74706c; }
<div>
  <input type="radio" name="purchaseVal" checked />
  <label>Label 1</label>
</div>

<div>
  <input type="radio" name="purchaseVal" />
  <label>Label 2</label>
</div>


推荐阅读