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

时间:2019-02-21 16:35:12

标签: javascript reactjs antd

我有一个主要组件和一个子组件,在这里我使用antd表。 该代码不会引发任何异常,并且所选的id可以正确地流到主要组件。

但是,单击复选框后它们会被清除,所以我不确定这里缺少什么

主要组成部分

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;

子组件

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;

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为子组件期望使用selectedRows道具,但主要组件没有将其传递给它。

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

因此,当您选择某项内容时,父项会通过onRowSelect属性更新其状态。但是它忘记通过selectedRows道具将更新后的状态发送回孩子。因此,孩子不知道已选择了哪一行,并且不知道默认未检查行为的后备。

要解决此问题,只需在主要组件中将PageTemplateIds状态作为selectedRows属性传递即可。

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