问题:
实现ant.design form组件自定义主要是实现value接口,即能通过form.props直接获取组件的value
实现方案:
this.props.onChange()方法,这个方法是组件经过getFieldDecorator包装后就会有的一个方法。通过该方法可以将自定义组件的值传递给form
代码实现
import React from 'react';
import {Form, Select} from 'antd';
import {formItemLayout} from './constants';
import MapBuilder from "./map";
const FormItem = Form.Item;
export default (field, form) => {
const {getFieldDecorator} = form;
// form.setFields({locations:'去2312'})
return (
<FormItem
{...formItemLayout}
id={field.id}
key={field.id}
label={field.label ? `${field.label}:` : ''}
hasFeedback
>
{getFieldDecorator(field.id, {
initialValue: field.defaultValue,
rules: field.rules,
})(
<MapBuilder
location={field.location} geo ={field.defaultValue}/>
)}
</FormItem>)
}
import React from 'react';
import querystring from 'querystring';
import {Base, Map, Marker,} from 'rc-bmap';
const {Point, Size, Events} = Base;
let center = [100.13, 15.35];
let _ = require('lodash');
export default class MapBuilder extends React.Component {
constructor(props) {
super(props);
this.state = {
point: [],
};
this.dragend = this.dragend.bind(this);
this.getPoint = this.getPoint.bind(this);
}
componentWillMount() {
if (this.props.location){
// let geo =this.props.geo?this.props.geo.spli
this.getPoint();
}
}
componentDidUpdate(prevProps) {
if (this.props.location != prevProps.location) {
this.getPoint();
}
}
getPoint() {
const str = querystring.encode({
code: 'utf-8',
q: this.props.location,
});
fetch(`https://nominatim.openstreetmap.org/search?q=${str}&format=geocodejson`)
.then(response => response.json())
.then((body) => {
if (body.features.length > 0) {
this.props.onChange(body.features[0].geometry.coordinates);
this.setState({point: [body.features[0].geometry.coordinates,]});
}
});
}
dragend(value) {
//该操作会将值传给form
this.props.onChange([value.point.lng, value.point.lat]);
}
getMakers() {
let children = [];
let point = this.state.point;
if (!point || point.length < 1) {
return children;
}
center = [point[0][0], point[0][1]];
for (let i in point) {
children.push(
<Marker dragging>
<Point lng={point[i][0]} lat={point[i][1]}/>
<Events
dragend={this.dragend}
/>
</Marker>
)
}
return children;
}
render() {
const children = this.getMakers();
let zoom = 6;
if (this.state.point && this.state.point.length > 0) {
zoom = 9;
}
return (
<div style={{height: 400}}>
<Map
ak="WAeVpuoSBH4NswS30GNbCRrlsmdGB5Gv"
zoom={zoom}
scrollWheelZoom
>
<Point name="center" lng={center[0]} lat={center[1]}/>
{children}
</Map>
</div>
)
}
}
;