需求:
- 选择大厦,把选择完大厦id传给楼层下拉列表,选择大厦请求楼层列表,互相可搜索
- 大厦没有配置楼层时,做校验
问题
新增编辑时只传选择完的楼层id,编辑回显后台给2个id,select封装成form表单子组件使用问题。
解决
form表单父组件
if (key === "floor_ids") {
return (
<Form.Item label="所在地区" className="panel-li-title">
{getFieldDecorator(`floor_ids`, {
//无用值 为了展示数据
initialValue: {},
rules: [
{
required: true,
message: "",
},
],
})(
// 所在地区大厦和楼层的组件
<FloorSelect2
form={form}
// 编辑的时候 拿到了data中 后台返回大厦和楼层的id 传给子组件
data={data}
></FloorSelect2>
)}
</Form.Item>
);
}
select子组件
1.初始化定义两个数组,buildList大厦列表 floorList楼层列表
state = {
// 所在地区逻辑修改
buildList: [], //大厦列表
floorList: [], //楼层列表};
2.定义个请求大厦列表的函数
// 这是楼层的change方法
componentDidMount() {
this.init();
}
init = () => {
//获取大厦列表
FloorguideAction.floorGuideMeetingBuildList({}).then((results) => {
console.log(results);
let { data = [] } = results;
if (!results.success) {
message.error("接口错误", 0.5);
return;
}
this.setState({
buildList: data,
});
});
};
render中遍历buildList数据渲染到大厦下拉框中
<Form.Item> {/* 拿到大厦id 这是传递的key*/} {getFieldDecorator(`build_id`, { // 这是默认值 initialValue: data.build_id, rules: [ { required: true, message: "大厦不能为空", }, ], })( <Select style={{ minWidth: "3.3rem", width: "3.3rem", marginRight: "0.12rem", }} onChange={(value) => { setFieldsValue({ floor_id: void 0, }); // 在切换选择大厦时,把选择完的大厦id传给了楼层请求接口的函数这样就能带过去这个id this.getFloorList(value); // 在选择大厦时,清除掉楼层的数据 }} placeholder="请选择大厦" showSearch filterOption={(input, option) => option.props.children .toLowerCase() .indexOf(input.toLowerCase()) >= 0 } > {buildList.map((item, index) => ( <Option key={index} value={item.id}> {item.cn_name} </Option> ))} </Select> )} </Form.Item>
4.定义一个楼层请求接口的函数 并赋值
// 楼层列表
getFloorList = (id) => {
MeetingAction.floorList({ id }).then((results) => {
let { data = [] } = results;
if (!results.success) {
message.error("接口错误", 0.5);
return;
}
this.setState({
floorList: data,
});
});
};
5.render中楼层渲染数据
<Form.Item style={{ width: "100%" }}>
{getFieldDecorator(`floor_id`, {
// 这个data是从父组件传递过来的,data是编辑时候返显的data数据 ,initialValue代表默认值 在编辑的时候回显数据使用的
initialValue: data.floor_id,
rules: [
{
required: true,
message: "未配置楼层",
},
],
})(
<Select
style={{
flexGrow: 1,
width: "100%",
}}
placeholder="请选择楼层"
showSearch
filterOption={(input, option) =>
option.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{floorList.map((item, index) => (
<Option key={item.id} value={item.id}>
{item.cn_name}
</Option>
))}
</Select>
)}
</Form.Item>
componentDidUpdate(prevProps, prevState) {
if (!_.isEqual(prevProps.data, this.props.data)) {
let { build_id } = this.props.data;
// 这个是在页面刷新就更新的生命周期函数,因为大厦列表的函数在init的时候更新的,楼层是基于切换选择大厦列表才请求的接口,所以大厦列表更新了 这个请求没有更新导致只展示id 所以在这个刷新就更新state的生命周期函数里更新一下这个请求函数
this.getFloorList(build_id);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。