如何将CSS应用于redux-form字段?

时间:2017-12-16 18:08:10

标签: css reactjs redux-form

如何将任何类型的CSS应用于redux-form Field组件? className和class被静默忽略:

        <div>
          <label>Name</label>
          <div>
            <Field
              className="form-input"
              name="formContactName"
              component="input"
              type="text"
              placeholder="Person to contact"
            />
          </div>
        </div>

我可以通过创建自定义组件来应用样式:

        <div>
          <label>Name</label>
          <div>
            <Field
              name="formContactName"
              component={ customInput }
            />
          </div>
        </div>

但这是一个主要的PITA,并且在很大程度上否定了首先使用redux-form的收益。我错过了什么吗?注意我直接在自定义组件中添加了className分配 - 我意识到我可以将它们作为Field中的道具发送。

我尝试在全球范围内设置input个样式,但它们也被忽略了。 redux-form网站文档告诉你使用该装备你需要知道的一切,但没有提到我能看到的CSS ......

谢谢,

JB

编辑:这不是重复 - 指向的答案使用自定义输入组件。如上所述,我可以让它工作,但那时首先真的不需要redux-form。

@Jay:通过从在线文档中获取代码,我能够使用自定义组件:

class MyCustomInput extends Component {
  render() {
    const { input: { value, onChange } } = this.props
    return (
      <div>
        <label htmlFor="formContactName" className="col-sm-2 control-label">Name:</label>
        <div className="col-sm-10">
          <input
            id="formContactName"
            placeholder="Person to contact"
            className="form-control"
            type="text"
          />
        </div>
      </div>
    )
  }
}

然后,在redux-form Form代码中:

    <div>
      <label>Name</label>
      <div>
        <Field
          name="formContactName"
          component={ MyCustomInput }
        />
      </div>
    </div>

使用此方法,className的引导程序设置正常。

1 个答案:

答案 0 :(得分:0)

您的所有自定义道具都会传递到输入组件,因此您可以执行

const CustomTextField = props => {
  const { input, label, type, meta: { touched, error }, ...other } = props

  return (
    <TextField
      label={label}
      type={type}
      error={!!(touched && error)}
      helperText={touched && error}
      { ...input }
      { ...other }
    />
  )
}

然后你可以将任何道具,包括className传递给CustomTextField

<Field
  name="some"
  component={CustomTextField}
  className="css-applied"
/>