react+antd+Table里切换Switch改变状态onChange 传参
场景:table列表里面,操作用Switch切换状态。对应列改变
操作在colums里面
// 表格行const colums: ColumnsType<potentialType> = [{title: useLocale('创建时间'),dataIndex: 'creation_date',key: 'creation_date',align: 'center',render: (v: string, record: { creation_date: string }) => {return (<span>{record?.creation_date ? formatMonent(record.creation_date) : '-'}</span>);},},{title: useLocale('更新时间'),key: 'update_date',dataIndex: 'update_date',align: 'center',render: (v: string, record: { creation_date: string }) => {return (<span>{record?.creation_date ? formatMonent(record.creation_date) : '-'}</span>);},},{title: useLocale('状态'),key: 'is_contact',dataIndex: 'is_contact',align: 'center',render: (record: any) => (<span>{!record ? CONTACT_STATUS.NOTCONTACTED : CONTACT_STATUS.CONTACTED}</span>),},{title: '操作',dataIndex: 'action',key: 'action',align: 'center',render: (text: any, record: any, index: any) => {return (<Switch checkedChildren={useLocale("已联系")}unCheckedChildren={useLocale("未联系")}key={record.is_contact}defaultChecked={record.is_contact}onChange={(checked)=>handleContactChange(record,checked)}/>)}},];
handleContactChange 切换方法:
const handleContactChange = (record:any,checked:any) => {const params={id:record?.id,is_contact: checked}getClientRegister(params).then((data: any) => {if(data.results){message.success(data.msg);fetchcasualList({ ...listParams});}}) };
引用
return (<><Card><Content><Form form={form} wrapperCol={{ span: 3, offset: 12 }}><TabledataSource={casualList?.results || []}columns={columns}loading={loading}pagination={handlePagination}rowKey='id'/></Form></Content></Card></>)
重点讲一下Switch里面onChange方法,传参的时候,自定义的参数,一定要用回调的方式。如果传参传的参数是本身有的,比如checked,就直接写:
antd官网https://ant.design/components/switch-cn#api


其次:选中Switch,根据刚进列表,Switch就根据请求的数据来显示开关,可以设置属性defaultChecked
注意这里defaultChecked不能写死,因为写死之后点击按钮时无法切换的。所以此处设置了key。key={record.is_contact}
记得请求结束后刷新列表,重新发起列表请求。
ok,这样解决列表问题。
js传参参考:https://blog.csdn.net/mChales_Liu/article/details/112558081
传参原理:https://www.cnblogs.com/xcsn/p/9158727.html