簡體   English   中英

使用antd表時,如果選中了復選框,則清除該復選框

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

我有一個主要組件和一個子組件,在這里我使用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;

發生這種情況是因為子組件期望使用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}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM