【发布时间】:2021-07-20 16:00:40
【问题描述】:
我有一些单选按钮,我的样式如下所示:
到目前为止,即使选中,它们看起来也一样。我想这样当你检查一个时,它不仅仅是一个环,而是用相同的颜色填充,如下所示:
我将如何在 React 中做到这一点?我可以在 CSS 中为元素添加背景颜色,但它不会是每个元素自己的颜色(除非我为每个元素创建一个单独的类,但考虑到我有很多这些,这似乎很长)。
代码如下:
import React from 'react';
import Options from './Options.jsx';
class Icing extends React.Component {
render() {
return (
<Options>
<input type="radio" className="circle" name="icing" defaultValue={1} id="white" style={{border: "10px solid #EFE5CE"}} />
<label class="radio" htmlFor="white"></label>
<input type="radio" className="circle" name="icing" defaultValue={2} id="pink" style={{border: "10px solid #EF959D"}} />
<label class="radio" htmlFor="pink"></label>
<input type="radio" className="circle" name="icing" defaultValue={3} id="red" style={{border: "10px solid #90DDD0"}} />
<label class="radio" htmlFor="red"></label>
</Options>
);
}
};
export default Icing;
谢谢!
编辑
好的,所以我添加了这个:
constructor() {
super();
this.state = {checked: false};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
并以这个按钮作为测试:
onChange={this.handleChange} checked={this.state.checked} style={{backgroundColor: this.state.checked ? 'red' : 'white'}}
果然,点击时背景确实发生了变化,但是当我点击另一个按钮时,它并没有恢复正常。我必须再次单击它才能使颜色消失。
【问题讨论】:
标签: javascript css reactjs