最新项目需要开始学习使用react,作为一个后端开发人员,javascript都很少写,这两天给我头发都薅了一大把...
问题描述 在用antd组件库的时候需要做一个红色背景的拒绝开关,本来想翻阅了一下网上大神们的解决方案,然后照抄一下,燃鹅...没有,没法自己捣鼓了一下搞出来了一个,大家有更好的方法欢迎交流分享,作为学了三天的新手解决方法,大家谨慎观摩。
新手解决方法 先贴一段调用的代码
import { CheckOutlined } from '@ant-design/icons';
import { Switch } from 'antd';
import RejectSwitch from './RejectSwitch';
const Showtswitch = () => {
return (
<>
<Switch
checkedChildren={<CheckOutlined />}
unCheckedChildren={<CheckOutlined />}
defaultChecked={false}
/>
<RejectSwitch/>
</>)
};
这个是修改背景颜色的switch开关
import { useState } from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Switch } from 'antd';
//加了一层壳子,使用onchange改变背景颜色
const RejectSwitch = () => {
//用了useState来设置初始的背景颜色,和变更状态
const [rejectStyle, setRejectStyle] = useState({
backgroundColor: 'rgba(0, 0, 0, 0.25)', hover: { backgroundColor: 'rgba(0, 0, 0, 0.45)' }
});
return (<Switch
style={rejectStyle }
onChange={(checked) => {
if (checked) {
setRejectStyle({
backgroundColor: 'red', hover: { backgroundColor: 'red' }
});
} else {
setRejectStyle({
backgroundColor: 'rgba(0, 0, 0, 0.25)', hover: { backgroundColor: 'rgba(0, 0, 0, 0.45)' }
});
}
} }
checkedChildren={<CloseOutlined />}
unCheckedChildren={<CloseOutlined />}
defaultChecked={false}
/>)
}
export default RejectSwitch
再贴一下useState的基本用处
state是一个组件所包含的状态信息,所谓“状态”,就是该组件任意时刻都存放的各种数据。 useState最常用的就是,当组件更新state时,可以记录变更新后的数据,动态调整触发组件的重新渲染。例如,希望在组件点击、聚焦时可以记录把这些数据作为局部变量存放,进行重新渲染。
新的一天
又学习了一下,更新一版可以设置任意颜色的Swtich。
然后还发现上一版有bug,style直接固定了backgroundcolor的颜色,hover:{}的写法不对,请教了一下搜索引擎,用css加!important就可以覆盖之前的属性,然后再增加一个传参,就可以达到任意背景颜色的设置了:)
index.css加几个属性
.selfswtich-check {
background-color: red !important;
}
.selfswtich-check:hover {
background-color: #ffad8e !important;
}
.selfswtich-uncheck {
background-color: rgba(0, 0, 0, 0.25) !important;
}
.selfswtich-uncheck:hover {
background-color: rgba(0, 0, 0, 0.45) !important;
}
这个是js
import { useState } from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Switch } from 'antd';
import './index.css'
const rejectclass = ['selfswtich-uncheck','selfswtich-check'] //css的两个类名,第一个是未选中,第二个是选中
const CommonColorSwtich=(props) => {
const [selfClass, setselfClass] = useState(
props.selfDefiningColor != undefined ? props.selfDefiningColor[0] : undefined
);
return (<Switch
className={selfClass}
onChange={(checked) => {
if (selfClass != undefined) { //没有设置的时候不会报错,显示默认的蓝色
if (checked) {
setselfClass(
props.selfDefiningColor[1]
);
} else {
setselfClass(
props.selfDefiningColor[0]
);
}
}
}}
checkedChildren={<CloseOutlined />}
unCheckedChildren={<CloseOutlined />}
defaultChecked={false}
/>)
}
const RejectSwitch = () => {
return (<CommonColorSwtich selfDefiningColor={rejectclass } />)
}
export default RejectSwitch