React Redux表单 - 模态中的预加载值,并将更改后的值传递给父

时间:2018-01-02 13:27:56

标签: reactjs redux react-redux redux-form

我正在实现在父组件内部调用的基于redux格式的模态。当打开模态时,父组件通过props将变量(myVariable)传递给子模态。该值在模态内的输入字段中为PRELOADED。

当用户更改输入字段中的值,并提交模态时,模态关闭,值将传递给父组件并更新最初传递给模态的父组件值。

PARENT COMPONENT

//import statements

export class ParentComponent extends Component {
  constructor (props) {
    super(props)

    this.state = {
      isOpenModal: false
    }

    this.submitAction = this.submitAction.bind(this)
  }

  submitAction = (values) => {
    console.log('submit action ', values)
  }

  render () {
    const {isOpenModal} = this.state
    const { myVariable } = this.props

    return (
      <div>
        { myVariable }

        <MyModal
          isOpenModal={isOpenModal}
          onSave={this.handleSave}
          myVariable={myVariable}
        />
      </div>
    )
  }
}

const formName = 'setMyForm'
const selector = formValueSelector(formName)

export const mapStateToProps = (state) => {
  return {
      //TODO
  }
}

const SetMyForm = connect(mapStateToProps)(ParentComponent)

export default reduxForm({
  form: formName,
  onSubmitFail: focusOnField(formName)
})(ParentComponent) 

儿童模式组件

//import statements - react, redux, redux form

let initialValues = {}
export class MyModal extends Component {
  constructor (props) {
    super(props)
    const {isOpenModal} = this.props
    this.state = {
      isOpenModal
    }

    this.handleSubmit = this.handleSubmit.bind(this)
  }

  handleSubmit (values) {
    const { myVariable } = values
  }

  render () {
    const { isOpenModal, myVariable } = this.props
    initialValues.myVariable = myVariable

    return (
      <CustomModal 
        <form onSubmit={handleSubmit(this.handleSubmit)}>
            <div>
            <Field
                  name='myVariable'
                  label='TEST'
                  type='text'
                  component={renderInputField}
                  />
            </div>
            <div>
              <div>
                <button type='submit' value='Save' />
              </div>
            </div>

        </form>
      </CustomModal>
    )
  }
}

MyModal.propTypes = {
  isOpenModal: PropTypes.bool.isRequired
}

const formName = 'modalForm'
const selector = formValueSelector(formName)

const mapStateToProps = (state) => {
  return {
     initialValues: {
       myVariable: selector(state, 'myVariable'),
     }
  }
}

const MyModalComp = connect(mapStateToProps)(MyModal)

export default reduxForm({
  form: formName,
  initialValues: initialValues,
  onSubmitFail: focusOnField(formName)

})(MyModalComp)

此代码中缺少什么?

0 个答案:

没有答案