antd design中switch二次封装(switchGroup)

项目中有用到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} />

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容