
项目中有用到switch组,但是antd没有提供对应的组件,所以打算自己封装一下。
当然不使用的话也能快速开发,但是个人不喜欢某个组件使用多次,然后再存很多状态的代码,这样不是很优雅。
switchGroup.js
import React from 'react'
import { Switch } from 'antd'
export default const switchGroup = ({ onChange, data, value }) => {
console.log(value);
let resultTmp = [];
data.map((item, index) => {
let isChecked = value.includes(item.type);
resultTmp.push(<Switch
key={"switch" + index}
style={{ margin: "0 4px" }}
checkedChildren={item.name}
unCheckedChildren={item.name}
onChange={onChange.bind(this, item.type, value)}
checked={isChecked}
/>);
});
return resultTmp;
}
使用的组件部分代码
const typeArr = [ //渲染源
{ type: 1, name: "游戏" },
{ type: 2, name: "动画" },
{ type: 3, name: "艺术" },
{ type: 4, name: "音乐" },
{ type: 5, name: "故事" },
{ type: 6, name: "模拟" },
{ type: 7, name: "学科" }
];
handleSwitchChange = (type, valueArr, value) => {//switch发生改变
let projectTags = valueArr
if (value) {
projectTags.push(type)
} else {
if (valueArr.includes(type)) {
projectTags.splice(projectTags.indexOf(type), 1)
}
}
this.setState({
projectTags
}); }
<RenderSwitch value={projectTags} data={typeArr} onChange={this.handleSwitchChange} />