如何使用redux-form进行语义-ui-react?

nbk*_*ope 5 semantic-ui redux-form semantic-ui-react

现在我使用ReduxForm的Field组件并应用原始语义UI类.但后来我遇到了Semantic UI React,它使事情变得更容易 - 你可以使用具有语义ui风格的React组件.

您如何将ReduxForm与SemanticUIReact集成?

例如,我目前有类似的东西:

<Field name="gender" component="select" className="ui fluid dropdown">
  {genderOptions}
</Field>
Run Code Online (Sandbox Code Playgroud)

但是,我想将下面的语义UI React组件连接到redux-form:

<Form.Field control={Select} label='Gender' options={genderOptions} placeholder='Gender' />
Run Code Online (Sandbox Code Playgroud)

!注意Field来自redux-form,Form.Field来自语义-ui-react

小智 15

创建一个这样的组件:

import React, { PropTypes } from 'react'
import { Input } from 'semantic-ui-react'

export default function SemanticReduxFormField ({ input, label, meta: { touched, error, warning }, as: As = Input, ...props }) {
  function handleChange (e, { value }) {
    return input.onChange(value)
  }
  return (
    <div>
      <As {...input} value={input.value} {...props} onChange={handleChange} error={touched && error} />
      {touched && (warning && <span>{warning}</span>)}
    </div>
  )
}

SemanticReduxFormField.propTypes = {
  as: PropTypes.any,
  input: PropTypes.any,
  label: PropTypes.any,
  meta: PropTypes.any
}
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中调用您的字段,如下所示:

import { Form } from 'semantic-ui-react'
import { reduxForm, Field } from 'redux-form'

class MyComponent extends Component {
  render () {
    return (
      <Form>
        <Field component={SemanticUiField} as={Form.Select} name='firstname' multiple options={options} placeholder='Select...' />
      </Form>
    )
  }
}

export default reduxForm({...})(MyComponent)
Run Code Online (Sandbox Code Playgroud)