如何设置和获取redux-form字段的值

时间:2019-04-06 20:05:09

标签: reactjs redux react-admin

我想更改redux-form字段的值。我正在构建一个react-admin应用程序。我检查了其他问题和答案,但无法解决我的问题。

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} />
                <span>&nbsp;<code>x</code>&nbsp;</span>
                <Field
                    component={renderTextField}
                    name="longitude"
                    type="number"
                    value={value.lng}
                    {...rest} />
            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

您可以参考此"Selecting Form Values Example"

如果您想访问表单值,您的代码应该看起来像这样:

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)