简体   繁体   中英

How to set and get value of redux-form field

I want to change the value of redux-form 's <Field /> . I'm building a react-admin app. I checked other questions & answers but nothing able to fix my problem.

export class MapInput extends React.Component {
  constructor(props) {
    super(props);
  }

  handleChange(value) {
    // Here, I want to change the value of the fields (latitude and longitude)
  }

  render() {
    var { value } = this.state;
    return (
      <div style={{marginTop: 15}}>
        <TitleText text="Address" />
        <MapView
          draggable={true}
          zoom={DefaultZoom}
          position={/* Also here, I need to get values from the fields as {lat: .., lng: ...} */}
          onChange={this.handleChange.bind(this)} />

        <Field
          component={renderTextField}
          name="latitude" type="number"
          value={value.lat}
          {...rest} />
        <Field
          component={renderTextField}
          name="longitude"
          type="number"
          value={value.lng}
          {...rest} />
      </div>
    );
  }
}

You can refer to this"Selecting Form Values Example"

You code should probably look like this if you wanna access the form values:

import { Field, reduxForm, formValueSelector } from 'redux-form'
import { compose } from 'redux'
import { connect } from 'react-redux'

class MapInput extends React.Component {
  constructor(props) {
    super(props)
  }

  handleChange = () => {
    // latitude and longitude are now in props
    console.log(this.props.latitude)
    console.log(this.props.longitude)
  }

  render() {
    const { value } = this.state
    const { latitude, longitude } = this.props
    return (
      <div style={{ marginTop: 15 }}>
        <TitleText text="Address" />
        <MapView
          draggable={true}
          zoom={DefaultZoom}
          position={{
            lat: latitude,
            lng: longitude
          }}
          onChange={this.handleChange}
        />

        <Field
          component={renderTextField}
          name="latitude"
          type="number"
          value={value.lat}
          {...rest}
        />
        <span>
          &nbsp;<code>x</code>&nbsp;
        </span>
        <Field
          component={renderTextField}
          name="longitude"
          type="number"
          value={value.lng}
          {...rest}
        />
      </div>
    )
  }
}

const selector = formValueSelector('formName')

export default compose(
  connect(state => {
    const { latitude, longitude } = selector(state, 'latitude', 'longitude')
    return {
      latitude,
      longitude
    }
  }),
  reduxForm({ form: 'formName' })
)(MapInput)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM