2017-11-09 3 views
0

Redot Form 구성 요소에 PlotMap이라는 Google Maps 하위 구성 요소가 있습니다. 자식 구성 요소는지도 입력을 콜백 객체로 다시 전달합니다. 이지도 입력 개체를 제출할 때 양식 데이터에 포함시키고 싶습니다. 어떻게해야합니까? 숨겨진 필드를 사용합니까? Redux Form의 놀라운 동작은 불투명하므로 개체를 추가 할 위치가 확실하지 않습니다.ReduxForm : 하위 구성 요소에서 맵 입력 추가

PlotForm 구성 요소 :

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { Field, reduxForm } from 'redux-form'; 
import * as actions from '../../actions'; 
import { Link } from 'react-router'; 
import PlotMap from './plotMap'; 

const renderField = ({ 
    input, 
    label, 
    type, 
    meta: { touched, error, warning } 
}) => (
    <fieldset className="form-group"> 
     <label htmlFor={input.name}>{label}</label> 
     <input className="form-control" {...input} type={type} /> 
     {touched && error && <span className="text-danger">{error}</span>} 
    </fieldset> 
); 

class PlotForm extends Component { 
    constructor(props) { 
     super(props); 
     this.handleFormSubmit = this.handleFormSubmit.bind(this); 
    } 

    handleFormSubmit(props) { 
     this.props.addPlot(props); 
    } 

    render() { 
     const { handleSubmit } = this.props; 
     const user = JSON.parse(localStorage.getItem('user')); 
     return (
      <div className="form-container text-center"> 
       <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> 
        <Field 
         name="name" 
         component={renderField} 
         type="text" 
         label="Plot Name" 
        /> 
        {user && 
         user.role === 3 && (
          <Field 
           name="company" 
           component={renderField} 
           type="text" 
           label="Company" 
          /> 
         )} 
        <Field 
         name="grower" 
         component={renderField} 
         type="text" 
         label="Grower" 
        /> 
        <Field 
         name="variety" 
         component={renderField} 
         type="text" 
         label="Variety" 
        /> 
        <Field 
         name="variety2" 
         component={renderField} 
         type="text" 
         label="Variety 2" 
        /> 
        <Field 
         name="planted" 
         component={renderField} 
         type="date" 
         label="Date Planted" 
        /> 
        <hr /> 
        <PlotMap getGeoJSON={GeoJSON => console.log(GeoJSON)} /> 
        <div className="form-group"> 
         <span> 
          <label>&nbsp;</label> 
          <button type="submit" className="btn btn-primary"> 
           Add Plot 
          </button> 
         </span> 
        </div> 
       </form> 
       <hr /> 
       <div> 
        {this.props.errorMessage && 
         this.props.errorMessage.plots && (
          <div className="error-container"> 
           Oops! {this.props.errorMessage.plots} 
          </div> 
         )} 
       </div> 
      </div> 
     ); 
    } 
} 

function mapStateToProps(state) { 
    return { 
     errorMessage: state.plots.error 
    }; 
} 

PlotForm = reduxForm({ form: 'plot', validate })(PlotForm); 
export default connect(mapStateToProps, actions)(PlotForm); 

PlotMap 구성 요소 :

아시다시피
import React, { Component } from 'react'; 
const { compose, withProps } = require('recompose'); 
const { withScriptjs, withGoogleMap, GoogleMap } = require('react-google-maps'); 
const { 
    DrawingManager 
} = require('react-google-maps/lib/components/drawing/DrawingManager'); 

const editTrack = polygon => { 
    let GeoJSON = { 
     type: 'Feature', 
     geometry: { 
      type: 'Polygon', 
      coordinates: [] 
     }, 
     properties: {} 
    }; 
    for (let point of polygon.getPath().getArray()) { 
     GeoJSON.geometry.coordinates.push([point.lng(), point.lat()]); 
    } 
    return GeoJSON; 
}; 

const PlotMap = compose(
    withProps({ 
     googleMapURL: 
      'https://maps.googleapis.com/maps/api/js?key=myKey&v=3.exp&libraries=geometry,drawing,places', 
     loadingElement: <div style={{ height: `100%` }} />, 
     containerElement: <div style={{ height: `400px` }} />, 
     mapElement: <div style={{ height: `100%` }} /> 
    }), 
    withScriptjs, 
    withGoogleMap 
)(props => (
    <GoogleMap 
     defaultZoom={8} 
     defaultCenter={new google.maps.LatLng(32.095, 35.398)}> 
     <DrawingManager 
      onPolygonComplete={polygon => { 
       polygon.setEditable(true); 
       props.getGeoJSON(editTrack(polygon)); 
       google.maps.event.addListener(polygon.getPath(), 'insert_at', function(
        index, 
        obj 
       ) { 
        props.getGeoJSON(editTrack(polygon)); 
       }); 
       google.maps.event.addListener(polygon.getPath(), 'set_at', function(
        index, 
        obj 
       ) { 
        props.getGeoJSON(editTrack(polygon)); 
       }); 
      }} 
      defaultDrawingMode={google.maps.drawing.OverlayType.POLYGON} 
      defaultOptions={{ 
       drawingControl: true, 
       drawingControlOptions: { 
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, 
        position: google.maps.ControlPosition.TOP_CENTER, 
        drawingModes: [google.maps.drawing.OverlayType.POLYGON] 
       } 
      }} 
     /> 
    </GoogleMap> 
)); 

export default PlotMap; 
+0

나는 PlotMap의 인터페이스 (소품)에 대한 자세한 정보가 필요합니다. –

+1

'const user = JSON.parse (localStorage.getItem ('user'));'를'componentWillMount()'또는 생성자로 이동 시키면 각 렌더에서 호출하지 않아도됩니다. 더 나아가 이것을 처리하는 redux 미들웨어를 만들어서 저장소에로드하십시오. –

+0

감사합니다, @ OriDrori. PlotMap에 대한 코드가 추가되었습니다. 기본적으로 폴리곤 객체를 처음 만들었을 때와 편집 할 때 콜백을 실행하여 새로운 GeoJSON 객체를 생성하고 반환합니다. –

답변

2

, 당신은 Field에 상기 component 소품으로 상태 비 저장 기능 ("renderField")을 전달할 수 있습니다. 함수에서 PlotMap을 랩핑하고 onChange 처리기 만 getGeoJSON에 연결할 수 있습니다.

OnChange 이벤트가 기본 입력 에서 발사 될 때마다 호출 될 콜백 :

onChange 방법으로 설명된다.

이 콜백은 redux-form에 필드 내용이 변경되었음을 알리고 redux 저장소를 업데이트합니다. onChange 이벤트를 사용하여 호출하는 대신 수동으로 호출하고 데이터를 전달할 수 있습니다.

예 REDUX 형태 (안된) :

<Field name="plotMap" component={({ input }) => (
    <PlotMap getGeoJSON={input.onChange} /> 
)}/> 
+0

여기 input.onChange 매개 변수가 어떻게 작동하는지 설명해 주시겠습니까? –

+0

또한 양식을 제출할 때 geoJSON 객체가 req.body.plotMap으로 액세스 할 수 있습니까? –

+1

몇 가지 정보를 추가하겠습니다. 그것은 표준 redux-form 필드이기 때문에 가능합니다. –

관련 문제