效果圖:

select 里的回填的值 和外面盒子的 數據保持同步更新。
運用到的知識點:
1、表單回填,雙向綁定。
2、redux
3、@修飾器
4、表單的 onValuesChange
5、select 的 onDeselect (就是select里的刪除回調)
頁面代碼:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Form, Select } from 'antd';
import { addTagList, onDeselect, onDeleteTagList } from '@/actions/select'
const { Option } = Select;
export default @connect( state => {
return{
optionList: state.select.optionList, //redux里存入數據(假裝是接收后台的數據)
tagList: state.select.tagList
}
},{
addTagList, //option進行添加
onDeselect, //select 回填里的刪除
onDeleteTagList //外面盒子 標簽里 X 刪除
})
@Form.create({
mapPropsToFields( {tagList} ) {
return {
select: Form.createFormField({
value: tagList.map( v => v.id), //雙向綁定,把taglist的數據給到select里
})
}
},
onValuesChange(props, { select }){
const { optionList } = props
if ( !select.length ) return //如果 select.length == true 就不進行添加的步驟了。
const obj = optionList.find( v => v.id == select.slice(-1)[0] )
props.addTagList(obj)
},
})
class Selects extends Component {
onDeleteTagList = option => {
this.props.onDeleteTagList(option)
}
// select回填里刪除數據
onDeselect = option => {
this.props.onDeselect(option)
}
render() {
const { getFieldDecorator } = this.props.form
const { optionList = [], tagList = [] } = this.props
return (
<div>
<Form>
<Form.Item>
{getFieldDecorator('select', {
rules: [{ required: true, message: 'Please select your select!' }],
})(
<Select mode="multiple" onDeselect={this.onDeselect} onChange={this.onChange}>
{
optionList.map( item => <Option value={item.id} key={item.id}>{item.name}</Option>)
}
</Select>,
)}
</Form.Item>
</Form>
<div>
{
tagList.map( item => {
return(
<span key={item.id} onClick={ ()=>this.onDeleteTagList(item)}>
{item.name}
<i style={{marginLeft: 5, marginRight: 5}}>X</i>
</span>
)
})
}
</div>
</div>
)
}
}
action 代碼:
const addTagList = option => {
return {
type: "SELECT_ADD_TAGLIST",
payload: option
}
}
const onDeselect = option => {
return {
type: "SELECT_ON_DESELECT",
payload: option
}
}
const onDeleteTagList = option => {
return {
type: "SELECT_ON_DELETE_TAGLIST",
payload: option
}
}
export {
addTagList,
onDeselect,
onDeleteTagList,
}
reducer 代碼
const defaultState = {
// 假裝optionList 是后台給的數據
optionList: [
{id: 'tiezhu', name: '鐵柱'},
{id: 'bangbang', name: '棒棒'},
{id: 'niaodan', name: '鳥蛋'},
],
// 用來存放 下面盒子的數據
tagList: []
}
export default function home (state = defaultState, action) {
//這里解構時候一定要注意,不能用const
let { tagList } = state
switch (action.type) {
// 添加
case 'SELECT_ADD_TAGLIST':
let index = tagList.findIndex( v => v.id == action.payload.id )
if( index == -1) tagList.push(action.payload)
return { ...state, tagList }
// select 回填數據刪除
case 'SELECT_ON_DESELECT':
tagList = tagList.filter(v => v.id !== action.payload)
return { ...state, tagList}
// tagList 數據刪除
case 'SELECT_ON_DELETE_TAGLIST':
tagList = tagList.filter(v => v.id !== action.payload.id)
return { ...state, tagList }
default:
return state
}
}
