如何在 Antd 表格中禁用行

huangapple go评论83阅读模式
英文:

How to Disable Row in Antd Table

问题

以下是您代码的翻译部分:

/* eslint-disable */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Button, Select, message, Radio, Table, Alert } from 'antd';
import _ from 'lodash';
import axios from 'axios';
import cookies from 'js-cookie';
import { _getCurrentBusiness } from '../../../utils/utils_business';
import { formatMessage } from 'umi-plugin-locale';

function DeleteConfirm(props) {
    
    const user_auth = cookies.getJSON('ckmsbp');
    const business = _getCurrentBusiness();
    const [radio, setRadio] = useState('all');
    const [role, setRole] = useState(null);
    const [chRole, setChrole] = useState(null); //changerole
    const [btn, setBtn] = useState(false);
    const isMounted = useRef(null);
    const roleRef = useRef(null);
    const spanAmount = { fontSize: '1rem', fontWeight: 500, marginLeft: '1rem' };
    
    useEffect(() => {
        isMounted.current = true;
        return () => isMounted.current = false;
    }, []);
    useEffect(() => {
        if (!_.isNil(props.roles)) {
            const updateRole = _.filter(props.roles, r => !_.eq(r.id, props.role.id));           
            setRole(updateRole); //tampil di select 
        }
    }, [props.roles]);
    
    const handleSubmit = async () => {
        let accountMeta = {};
        const body = { status: 'deleted' };
        const params = { _id: props.role.id };
        console.log('radio', radio);
        if (_.eq(radio, 'all')) {

            if (_.isNil(chRole)) {
                message.error('data can not empty');
                props.chVisible(null); //close modal
            }
            
            _.forEach(props.account, async acc => {
                let bus = [];
                if (!_.isNil(acc.business) && _.isString(acc.business)) bus = JSON.parse(acc.business);
                const find = _.findIndex(bus, b => {
                    return _.eq(b._id, business._id) && _.eq(b.role_capability, props.role.id);
                });
                bus[find].role_capability = chRole;
                acc.business = JSON.stringify(bus);
                accountMeta = {
                    value     : acc.business,
                    key       : 'business',
                    account_id: acc._id
                };
                await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token } });
            });
           
        } else if (_.eq(radio, 'manual')) {
            console.log('asd');
            
        } else if (_.eq(radio, 'delete')) {
            _.forEach(props.account, async acc => {
                let bus = [];
                if (!_.isNil(acc.business) && _.isString(acc.business)) bus = JSON.parse(acc.business);
                const find = _.findIndex(bus, b => _.eq(b._id, business._id) && _.eq(b.role_capability, props.role.id) );
                if (_.gt(find, -1)) {
                    acc.business = JSON.stringify([]);
                    accountMeta = {
                        value     : acc.business,
                        key       : 'business',
                        account_id: acc._id
                    };
                    await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token } });
                }                
            });
        }
         const deleteResult = await axios.put(`${API}/master`, body, { params, headers: { Authorization: user_auth.token } });
         if (!_.isNil(deleteResult) && _.isObject(deleteResult.data)) {
             let no = 1;
             let data = [];
             let updateRole = _.filter(props.roles, r => !_.eq(r.id, props.role.id));
             _.map(updateRole, role => {
                 role.no = no;
                 data.push(role);
                 no++;
             });
             props.data(data); //tampil di select 
             message.success('data updated!');
             props.chVisible(null); //close modal
         }
    }
    
    const onChange = data => {
        const value = data.target.value;
        setRadio(value);
    }

    const roleChange = data => {
        setChrole(data);
    }

    //props column diambil dari datasource
    const columns = [
      {
        title    : 'No',
        dataIndex: 'no',
        key      : 'no',
      },
      {
        title    : "Account's Name",
        dataIndex: 'name',
        key      : 'name',
      },
      {
        title    : 'Change Role',
        dataIndex: 'id',
        key      : 'action',
        render : (text, data) => renderButton(text, data) 
      },
    ];

    const handleClick = (e, data) => {
        setBtn(!btn);
        console.log('e', e);
        console.log('data', data);
    }

    const rowClassName = (record, index) => {
        console.log('record', record);
        console.log('index',index);
        
    }

    const renderButton = () => {
      let arrayAllow = [];
        arrayAllow.push(
          <Select
                showSearch
                key              = '1'
                size             = "small"
                placeholder      = "select"
                ref              = {roleRef}
                optionFilterProp = "children"
                style            = {{ width: 100 }}
                onChange         = {e => roleChange(e)} //handle change role
                filterOption     = {(input, option) => _.toLower(option.props.children).indexOf(_.toLower(input)) >= 0}
            >
                {
                    !_.isNil(role) && _.map(role, (newVal) => {
                        return (<Select.Option 
                                    key   = {newVal.id}
                                    title = {newVal.title}
                                    value = {newVal.id}>{newVal.title}
                                </Select.Option>)
                    })
                }
            </Select>
        )
        arrayAllow.push( <Button 
                            type    = {!btn ? "danger" : "primary"}
                            key     = '2'
                            icon    = {!btn ? "close" : "redo"}
                            size    = "small"
                            onClick = {e => handleClick(e, props.role.id)}
                         /> )
      return arrayAllow;
    }
    
    // R E N D E R I N G
    return(
      <div>
        <Modal
            title    = {`${formatMessage({id: 'ROLE_MANAGEMENT.DELETE_CONFIRM_TITLE'})} ${props.role.title}`}
            visible  = {props.visible}
            onOk     = {() => handleSubmit()}
            onCancel = {() => props.cancel(null) }
            width    = {800}
        >
          <p>{formatMessage({id : 'ROLE_MANAGEMENT.DELETE_CONFIRM_STATEMENT', title: props.role.title})}</p>
            <div style={{marginBottom: '1rem'}}>
                <Radio.Group onChange = {e => onChange(e)} value={radio}>
                    <Radio value="all">Changed All of people  </Radio>
                    <Radio value="manual">Changed people manually</Radio>
                    <Radio value="delete">Total delete           </Radio>
                </Radio.Group>
            </div>

          { _.eq(radio, 'all')

<details>
<summary>英文:</summary>

so I worked on a project using react js with umi js and antd as additional dependencies,

I had a problem when I got the task to disable each row in the antd table,

I tried to read the documentation antd but got nothing,

is it possible that you can do that? or there is another possible way to doing that

Thank you for the help

here&#39;s my code : 

/* eslint-disable */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Button, Select, message, Radio, Table, Alert } from 'antd';
import _ from 'lodash';
import axios from 'axios';
import cookies from 'js-cookie';
import {_getCurrentBusiness} from '../../../utils/utils_business';
import {formatMessage } from 'umi-plugin-locale';

function DeleteConfirm (props) {

const user_auth           = cookies.getJSON(&#39;ckmsbp&#39;);
const business            = _getCurrentBusiness();
const [radio, setRadio]   = useState(&#39;all&#39;);
const [role, setRole]     = useState(null);
const [chRole, setChrole] = useState(null); //changerole
const [btn, setBtn]       = useState(false);
const isMounted           = useRef(null);
const roleRef             = useRef(null);
const spanAmount          = {fontSize: &#39;1rem&#39;, fontWeight: 500,marginLeft: &#39;1rem&#39;}
useEffect( () =&gt; {
isMounted.current = true;
return () =&gt; isMounted.current = false;
}, [])
useEffect( () =&gt; {
if(!_.isNil(props.roles)) {
const updateRole = _.filter(props.roles, r =&gt; !_.eq(r.id, props.role.id) );           
setRole(updateRole); //tampil di select 
}
}, [props.roles]);
const handleSubmit = async () =&gt; {
let   accountMeta = {}
const body        = {status: &#39;deleted&#39;}
const params      = { _id: props.role.id}
console.log(&#39;radio&#39;, radio);
if(_.eq(radio, &#39;all&#39;)){
if(_.isNil(chRole)) {
message.error(&#39;data can not empty&#39;)
props.chVisible(null); //close modal
}
_.forEach(props.account, async acc =&gt; {
let bus = [];
if( !_.isNil(acc.business) &amp;&amp; _.isString(acc.business) ) bus = JSON.parse(acc.business);
const find = _.findIndex(bus, b =&gt; {
return _.eq(b._id, business._id) &amp;&amp; _.eq(b.role_capability, props.role.id)
})
bus[find].role_capability = chRole;
acc.business = JSON.stringify(bus)
accountMeta = {
value     : acc.business,
key       : &#39;business&#39;,
account_id: acc._id
}
await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token}});
})
} else if( _.eq(radio, &#39;manual&#39;)){
console.log(&#39;asd&#39;);
} else if (_.eq(radio, &#39;delete&#39;)){
_.forEach(props.account, async acc =&gt; {
let bus = [];
if( !_.isNil(acc.business) &amp;&amp; _.isString(acc.business) ) bus = JSON.parse(acc.business);
const find = _.findIndex(bus, b =&gt; _.eq(b._id, business._id) &amp;&amp; _.eq(b.role_capability, props.role.id) )
if(_.gt(find, -1)){
acc.business = JSON.stringify([])
accountMeta = {
value     : acc.business,
key       : &#39;business&#39;,
account_id: acc._id
}
await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token}});
}                
})
}
const deleteResult = await axios.put(`${API}/master`, body, { params, headers: { Authorization: user_auth.token}});
if(!_.isNil(deleteResult) &amp;&amp; _.isObject(deleteResult.data)){
let no         = 1;
let data       = []
let updateRole = _.filter(props.roles, r =&gt; !_.eq(r.id, props.role.id));
_.map(updateRole, role =&gt; {
role.no = no;
data.push(role)
no++
});
props.data(data); //tampil di select 
message.success(&#39;data updated!&#39;)
props.chVisible(null); //close modal
}
}
const onChange  = (data) =&gt; {
const value = data.target.value
setRadio(value);
}
const roleChange = (data) =&gt; {
setChrole(data)
}
//props column diambil dari datasource
const columns = [
{
title    : &#39;No&#39;,
dataIndex: &#39;no&#39;,
key      : &#39;no&#39;,
},
{
title    : &#39;Account\&#39;s Name&#39;,
dataIndex: &#39;name&#39;,
key      : &#39;name&#39;,
},
{
title    : &#39;Change Role&#39;,
dataIndex: &#39;id&#39;,
key      : &#39;action&#39;,
render : (text, data) =&gt; renderButton(text, data) 
},
];
const handleClick = (e, data) =&gt; {
setBtn(!btn)
console.log(&#39;e&#39;, e);
console.log(&#39;data&#39;, data);
}
const rowClassName = (record, index) =&gt; {
console.log(&#39;record&#39;, record);
console.log(&#39;index&#39;,index);
}
const renderButton = () =&gt; {
let arrayAllow = [];
arrayAllow.push(
&lt;Select
showSearch
key              = &#39;1&#39;
size             = &quot;small&quot;
placeholder      = &quot;select&quot;
ref              = {roleRef}
optionFilterProp = &quot;children&quot;
style            = {{ width: 100 }}
onChange         = {(e) =&gt; roleChange(e)} //handle change role
filterOption     = {(input, option) =&gt; _.toLower(option.props.children).indexOf(_.toLower(input)) &gt;= 0}
&gt;
{
!_.isNil(role) &amp;&amp; _.map(role, (newVal) =&gt; {
return (&lt;Select.Option 
key   = {newVal.id}
title = {newVal.title}
value = {newVal.id}&gt;{newVal.title}
&lt;/Select.Option&gt;)
})
}
&lt;/Select&gt;
)
arrayAllow.push( &lt;Button 
type    = {!btn ? &quot;danger&quot; : &quot;primary&quot;}
key     = &#39;2&#39;
icon    = {!btn ? &quot;close&quot; : &quot;redo&quot;}
size    = &quot;small&quot;
onClick = {(e) =&gt; handleClick(e, props.role.id)}
/&gt; )
return arrayAllow
}
// R E N D E R I N G
return(
&lt;div&gt;
&lt;Modal
title    = {`${formatMessage({id: &#39;ROLE_MANAGEMENT.DELETE_CONFIRM_TITLE&#39;})} ${props.role.title}`}
visible  = {props.visible}
onOk     = {() =&gt; handleSubmit()}
onCancel = {() =&gt; props.cancel(null) }
width    = {800}
&gt;
&lt;p&gt;{formatMessage({id : &#39;ROLE_MANAGEMENT.DELETE_CONFIRM_STATEMENT&#39;, title: props.role.title})}&lt;/p&gt;
&lt;div style={{marginBottom: &#39;1rem&#39;}}&gt;
&lt;Radio.Group onChange = {(e) =&gt; onChange(e)} value={radio}&gt;
&lt;Radio value=&quot;all&quot;   &gt;Changed All of people  &lt;/Radio&gt;
&lt;Radio value=&quot;manual&quot;&gt;Changed people manually&lt;/Radio&gt;
&lt;Radio value=&quot;delete&quot;&gt;Total delete           &lt;/Radio&gt;
&lt;/Radio.Group&gt;
&lt;/div&gt;
{ _.eq(radio, &#39;all&#39;) &amp;&amp; 
&lt;div&gt;
&lt;Select
showSearch
ref              = {roleRef}
size             = &quot;large&quot;
style            = {{ width: 200 }}
placeholder      = {formatMessage({id: &#39;ACCOUNT.PLCHOLDER_ROLE&#39;})}
optionFilterProp = &quot;children&quot;
onChange         = {(e) =&gt; roleChange(e)} //handle change role
filterOption     = {(input, option) =&gt; _.toLower(option.props.children).indexOf(_.toLower(input)) &gt;= 0}
&gt;
{
!_.isNil(role) &amp;&amp; _.map(role, (newVal) =&gt; { 
return ( &lt;Select.Option 
key   = {newVal.id}
title = {newVal.title}
value = {newVal.id}
&gt;{newVal.title}
&lt;/Select.Option&gt; )
})
}
&lt;/Select&gt;
&lt;span style={spanAmount}&gt;{`Total amount of people which have role ${props.role.title} : ${_.size(props.account)}`}&lt;/span&gt;
&lt;/div&gt;
}
{ _.eq(radio, &#39;manual&#39;) &amp;&amp; &lt;Table 
dataSource   = {props.account}
rowClassName = {rowClassName}
columns      = {columns}
pagination   = {{ pageSize: 50 }}
scroll       = {{ y: 250 }}
/&gt; 
}
{ _.eq(radio, &#39;delete&#39;) &amp;&amp; &lt;Alert
message     = &quot;Attention!&quot;
description = {formatMessage({id: &#39;ROLE_MANAGEMENT.DELETE_CONFIRM_DELETE&#39;})}
type        = &quot;warning&quot;
showIcon
/&gt;
} 
&lt;/Modal&gt;
&lt;/div&gt;
)

}

export default DeleteConfirm;


*the picture that I intend to disable when clicked on the danger button
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/G2910.png
</details>
# 答案1
**得分**: 9
在Antd中,没有直接禁用行的简单方法,但你可以像下面这样通过一种变通方法来实现:
所以基本上当你点击**close**按钮时,你可以有一个状态,表示它是启用还是禁用,用一个布尔值表示。
所以每个记录都会有这个键。根据这个键,你可以添加一个className并将其样式设置为禁用。
以下是一个示例代码片段:
**App.js**
```jsx
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Table } from "antd";
import "./styles.css";
function App() {
const dataSource = [
{
key: "1",
name: "Mike",
age: 32,
address: "10 Downing Street",
enabled: true
},
{
key: "2",
name: "John",
age: 42,
address: "10 Downing Street",
enabled: false
}
];
const columns = [
{
title: "Name",
dataIndex: "name",
key: "name"
},
{
title: "Age",
dataIndex: "age",
key: "age"
},
{
title: "Address",
dataIndex: "address",
key: "address"
}
];
return (
<>
<Table
dataSource={dataSource}
columns={columns}
rowClassName={record => !record.enabled && "disabled-row"}
/>
;
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

style.css

.disabled-row {
  background-color: #dcdcdc;
  pointer-events: none;
}

希望这种方法能让你更好地理解如何解决这个问题。

这里可以查看工作示例。

英文:

In Antd there is no simple way to disable a row, so you can do it as workaround like below

So basically when you click on close button you can have state whether its been enabled or disabled as a boolean value

so each record will have that key. so based on that you can add a className and style it as disabled.

Here is a sample code snippet

App.js

import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;
import &quot;antd/dist/antd.css&quot;;
import { Table } from &quot;antd&quot;;
import &quot;./styles.css&quot;;
function App() {
const dataSource = [
{
key: &quot;1&quot;,
name: &quot;Mike&quot;,
age: 32,
address: &quot;10 Downing Street&quot;,
enabled: true
},
{
key: &quot;2&quot;,
name: &quot;John&quot;,
age: 42,
address: &quot;10 Downing Street&quot;,
enabled: false
}
];
const columns = [
{
title: &quot;Name&quot;,
dataIndex: &quot;name&quot;,
key: &quot;name&quot;
},
{
title: &quot;Age&quot;,
dataIndex: &quot;age&quot;,
key: &quot;age&quot;
},
{
title: &quot;Address&quot;,
dataIndex: &quot;address&quot;,
key: &quot;address&quot;
}
];
return (
&lt;&gt;
&lt;Table
dataSource={dataSource}
columns={columns}
rowClassName={record =&gt; !record.enabled &amp;&amp; &quot;disabled-row&quot;}
/&gt;
;
&lt;/&gt;
);
}
const rootElement = document.getElementById(&quot;root&quot;);
ReactDOM.render(&lt;App /&gt;, rootElement);

style.css

.disabled-row {
background-color: #dcdcdc;
pointer-events: none;
}

I hope this way you will have better understanding of solving the problem

Working codesandbox

huangapple
  • 本文由 发表于 2020年1月3日 15:19:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定