class EditableCell extends React.Component {
getInput = () => {
if (this.props.inputType === 'number') {
return <InputNumber />;
}
return <Input />;
};
render() {
const {
editing,
dataIndex,
title,
inputType,
record,
index,
...restProps
} = this.props;
return (
<EditableContext.Consumer>
{(form) => {
const { getFieldDecorator } = form;
return (
<td {...restProps}>
{editing ? (
<FormItem style={{ margin: 0 }}>
{getFieldDecorator(dataIndex, {
rules: [{
required: true,
message: `请输入 ${title}!`,
}],
initialValue: record[dataIndex],
})(this.getInput())}
</FormItem>
) : restProps.children}
</td>
);
}}
</EditableContext.Consumer>
);
}
}
class EditableTable extends React.Component {
constructor(props) {
super(props);
this.state = { data, editingKey: '' };
this.columns = [
{
title: '期数',
dataIndex: 'installment',
width: '25%',
editable: true,
},
{
title: '利率',
dataIndex: 'interestRate',
width: '25%',
editable: true,
},
{
title: '操作',
dataIndex: 'operation',
render: (text, record) => {
const editable = this.isEditing(record);
return (
<div>
{editable ? (
<span>
<EditableContext.Consumer>
{form => (
<a
href="javascript:;"
onClick={() => this.save(form, record.key)}
style={{ marginRight: 8 }}
>
保存
</a>
)}
</EditableContext.Consumer>
<Popconfirm
title="确定取消?"
onConfirm={() => this.cancel(record.key)}
>
<a>取消</a>
</Popconfirm>
</span>
) : (
<div>
<a onClick={() => this.edit(record.key)}>编辑</a>
<Divider type="vertical" />
<Popconfirm title="Sure to delete?" onConfirm={() => this.onDelete(record.key)}>
<a href="javascript:;">Delete</a>
</Popconfirm>
</div>
)}
</div>
);
},
},
];
}
isEditing = (record) => {
return record.key === this.state.editingKey;
};
edit(key) {
this.setState({ editingKey: key });
}
onDelete = (key) => {
const newData = [...this.state.newData];
this.setState({ data: newData, editingKey: '' });
}
save(form, key) {
form.validateFields((error, row) => {
if (error) {
return;
}
const newData = [...this.state.data];
const index = newData.findIndex(item => key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, {
...item,
...row,
});
this.setState({ data: newData, editingKey: '' });
} else {
newData.push(data);
this.setState({ data: newData, editingKey: '' });
}
});
}
cancel = () => {
this.setState({ editingKey: '' });
};
render() {
const components = {
body: {
row: EditableFormRow,
cell: EditableCell,
},
};
const columns = this.columns.map((col) => {
console.log(col,5555555)
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
inputType: 'number',
dataIndex: col.dataIndex,
title: col.title,
editing: this.isEditing(record),
}),
};
});
return (
<Table
components={components}
dataSource={this.state.data}
columns={columns}
style={{width:'50%'}}
rowClassName="editable-row"
onRow={(record, index) => {
console.log(record,index)
}}
/>
);
}
}
const AddProducts = Form.create()(AddProduct);
export default AddProducts;
轻松入门 React 开发,React Router 4 与 Webpack 2 完美升级项目
了解课程