ant-design/components/table/SelectionBox.tsx

59 lines
1.5 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import Checkbox from '../checkbox';
import Radio from '../radio';
2017-11-21 13:48:37 +08:00
import { SelectionBoxProps, SelectionBoxState } from './interface';
2017-11-21 13:48:37 +08:00
export default class SelectionBox extends React.Component<SelectionBoxProps, SelectionBoxState> {
unsubscribe: () => void;
2017-11-21 13:48:37 +08:00
constructor(props: SelectionBoxProps) {
super(props);
this.state = {
checked: this.getCheckState(props),
};
}
componentDidMount() {
this.subscribe();
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
// eslint-disable-next-line class-methods-use-this
2017-11-21 13:48:37 +08:00
getCheckState(props: SelectionBoxProps) {
const { store, defaultSelection, rowIndex } = props;
let checked = false;
if (store.getState().selectionDirty) {
checked = store.getState().selectedRowKeys.indexOf(rowIndex) >= 0;
} else {
2018-12-07 16:17:45 +08:00
checked =
store.getState().selectedRowKeys.indexOf(rowIndex) >= 0 ||
defaultSelection.indexOf(rowIndex) >= 0;
}
return checked;
}
2019-08-05 18:38:10 +08:00
subscribe() {
const { store } = this.props;
this.unsubscribe = store.subscribe(() => {
const checked = this.getCheckState(this.props);
this.setState({ checked });
});
}
render() {
const { type, rowIndex, ...rest } = this.props;
const { checked } = this.state;
if (type === 'radio') {
2018-12-07 16:17:45 +08:00
return <Radio checked={checked} value={rowIndex} {...rest} />;
}
2019-08-05 18:38:10 +08:00
return <Checkbox checked={checked} {...rest} />;
}
}