方案:Sortable( react-sortablejs)+Form.Item
代码:
- sortable初始值initialDropDownValue:[0,1,2]
- sortable包裹Form.Item
<Sortable
options={{
group: 'shared',
chosenClass: 'chosen-item-cls',
handle: '.handle',
animation: 150,
}}
tag="div"
onChange={(order, sortable, evt) => {
this.setState({
initialDropDownValue: order,
});
}}
>
{formItems}
</Sortable>
- Form.Item基于sortable的initialDropDownValue生成
getFieldDecorator('keysDD', {
initialValue: this.state.initialDropDownValue,
});
const keysDD = getFieldValue('keysDD');
const Option = Select.Option;
const formItems = keysDD.map((k, index) => (
<div key={Number(k)} data-id={Number(k)} className="draggable_item">
<FormItem {...formItemLayout} required={false} key={Number(k)+1}>
<i
className="iconfont icon-sort"
style={{
fontSize: 12,
color: '#949ea8',
marginRight: 5,
cursor: 'pointer',
}}
/>
{getFieldDecorator(`DropDownListIndex[${k}]`, {
initialValue:Number(k)+1,
validateTrigger: ['onChange', 'onBlur'],
rules: [],
})(
<Input
placeholder="请输入索引"
style={{ width: 100, marginRight: 10 }}
maxLength={MAX_INDEX_LENGTH}
/>,
)}
</FormItem>
<FormItem {...formItemLayout} required={false} key={k}>
{getFieldDecorator(`DropDownListNames[${k}]`, {
validateTrigger: ['onChange', 'onBlur'],
rules: [
{
required: true,
whitespace: true,
message: '选项不能为空!',
},
],
})(
<Input
key="DropDownList"
placeholder="请输入"
style={{ width: '50%', marginRight: 23.5 }}
maxLength={50}
/>,
)}
<span style={{ width: '30%' }}>
<Radio
checked={k === this.state.DropDownListDefaultRadio}
value={k}
onChange={this.DropDownListDefaultRadio.bind(this)}
id="InputRadio"
name="InputRadio"
/>
</span>
<span style={{ marginRight: 28 }}>默认</span>
{keysDD.length > 1 ? (
<Icon
className="dynamic-delete-button"
type="minus-circle"
disabled={keysDD.length === 1}
onClick={() => this.DropDownRemove(k)}
/>
) : null}
</FormItem>
</div>
));
- 加的逻辑:根据最大项往后加([1,3,5,7]),保证增删完,值不会重复
DropDownAdd = () => {
this.setState({
initialDropDownValue: [...this.state.initialDropDownValue].concat(
Math.max(...this.state.initialDropDownValue) + 1,
),
});
};
- 减的逻辑
DropDownRemove = k => {
const { initialDropDownValue } = this.state;
this.setState({
initialDropDownValue: this.removeAndFixOrder(initialDropDownValue, k),
});
};
removeAndFixOrder = (arr = [], k) => {
if (k === undefined || k === null) return arr;
return arr
.map(i => {
if (i == k) return false;
return i;
})
.filter(j => j !== false);
};