简体   繁体   English

使用antd表时,如果选中了复选框,则清除该复选框

[英]When using antd table, with checkbox selection, the checkbox is cleared

I have a main component and a child component where I use antd table. 我有一个主要组件和一个子组件,在这里我使用antd表。 The code does not throw any exception, and the selected ids are flowing correctly to the main component. 该代码不会引发任何异常,并且所选的id正确地流向了主要组件。

However the checkboxes are cleared after clicking on them, so I am not sure what am I missing here 但是,单击复选框后,复选框将被清除,因此我不确定此处缺少什么

Main component 主要成分

import React, { Component } from 'react';
import { Input} from 'antd';
import Form from '../../components/uielements/form';
import Button from '../../components/uielements/button';
import Notification from '../../components/notification';
import { adalApiFetch } from '../../adalConfig';
import   ListPageTemplatesWithSelection  from './ListPageTemplatesWithSelection';


const FormItem = Form.Item;

class CreateModernSiteCollectionForm extends Component {
    constructor(props) {
        super(props);
        this.state = {Alias:'',DisplayName:'', Description:'', PageTemplateIds : []};
        this.handleChangeAlias = this.handleChangeAlias.bind(this);
        this.handleChangeDisplayName = this.handleChangeDisplayName.bind(this);
        this.handleChangeDescription = this.handleChangeDescription.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleRowSelect = this.handleRowSelect.bind(this);
    }

    handleRowSelect(ids) {
        this.setState({ PageTemplateIds: ids });
    }

    handleChangeAlias(event){
        this.setState({Alias: event.target.value});
    }

    handleChangeDisplayName(event){
        this.setState({DisplayName: event.target.value});
    }

    handleChangeDescription(event){
        this.setState({Description: event.target.value});
    }

    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let data = new FormData();
                //Append files to form data
                //data.append(

                const options = {
                  method: 'post',
                  body: JSON.stringify(
                    {
                        "Alias": this.state.Alias,
                        "DisplayName": this.state.DisplayName, 
                        "Description": this.state.Description
                    }),
                    headers: {
                            'Content-Type': 'application/json; charset=utf-8'
                    }                    
                };

                adalApiFetch(fetch, "/SiteCollections", options)
                  .then(response =>{
                    if(response.status === 201){
                        Notification(
                            'success',
                            'Site collection created',
                            ''
                            );
                     }else{
                        throw "error";
                     }
                  })
                  .catch(error => {
                    Notification(
                        'error',
                        'Site collection not created',
                        error
                        );
                    console.error(error);
                });
            }
        });      
    }

    render() {

          // rowSelection object indicates the need for row selection
          const handleRowSelect = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRowKeys);
            }

        };
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
        };
        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 14,
            offset: 6,
            },
        },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="Alias" hasFeedback>
                {getFieldDecorator('Alias', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your alias',
                        }
                    ]
                })(<Input name="alias" id="alias" onChange={this.handleChangeAlias} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Display Name" hasFeedback>
                {getFieldDecorator('displayname', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your display name',
                        }
                    ]
                })(<Input name="displayname" id="displayname" onChange={this.handleChangeDisplayName} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Description" hasFeedback>
                {getFieldDecorator('description', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your description',
                        }
                    ],
                })(<Input name="description" id="description"  onChange={this.handleChangeDescription} />)}
                </FormItem>

                <ListPageTemplatesWithSelection onRowSelect={this.handleRowSelect} />

                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">
                        Create modern site
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedCreateModernSiteCollectionForm = Form.create()(CreateModernSiteCollectionForm);
export default WrappedCreateModernSiteCollectionForm;

Child component 子组件

import React, { Component } from 'react';
import {  Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';

class ListPageTemplatesWithSelection extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    fetchData = () => {
        adalApiFetch(fetch, "/PageTemplates", {})
          .then(response => response.json())
          .then(responseJson => {
            if (!this.isCancelled) {
                const results= responseJson.map(row => ({
                    key: row.Id,
                    Name: row.Name
                  }))
              this.setState({ data: results });
            }
          })
          .catch(error => {
            console.error(error);
          });
      };


    componentDidMount(){
        this.fetchData();
    }

    render(){
        const columns = [
                {
                    title: 'Id',
                    dataIndex: 'key',
                    key: 'key',
                }, 
                {
                    title: 'Name',
                    dataIndex: 'Name',
                    key: 'Name',
                }
        ];

        const rowSelection = {
            selectedRowKeys: this.props.selectedRows,
            onChange: (selectedRowKeys) => {
              this.props.onRowSelect(selectedRowKeys);
            }
          };


        return (
            <Table rowSelection={rowSelection}  columns={columns} dataSource={this.state.data} />
        );
    }
}

export default ListPageTemplatesWithSelection;

This is happening because child component is expecting the selectedRows prop but the main component is not passing it to it. 发生这种情况是因为子组件期望使用selectedRows道具,但主要组件没有将其传递给它。

const rowSelection = {
    selectedRowKeys: this.props.selectedRows,
    //-----------------------------^^--------
    onChange: (selectedRowKeys) => {
        this.props.onRowSelect(selectedRowKeys);
    }
};

So when you select something, parent updates its state via onRowSelect prop. 因此,当您选择某些内容时,父对象会通过onRowSelect道具更新其状态。 But it forgets to send the updated state back to the child via selectedRows prop. 但是它忘记了通过selectedRows属性将更新后的状态发送回给孩子。 So the child doesn't know what row's have been selected and fallbacks to default unchecked behavior. 因此,孩子不知道已选择了哪一行,并且不知道默认未检查行为的后备。

To fix it, just pass the PageTemplateIds state as selectedRows prop in your main component: 要解决此问题,只需在您的主要组件中将PageTemplateIds状态作为selectedRows道具传递:

<ListPageTemplatesWithSelection 
    onRowSelect={this.handleRowSelect} 
    selectedRows={this.state.PageTemplateIds}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM