Redux 形式 <Field> 中的类名

className in <Field> in Redux Form

我创建了一个 redux-form,我想将 className 添加到每个字段以使用 css 自定义它们。 每个字段的代码是:

<Form onSubmit={handleSubmit(requestAccountsFilter)}>
        <FormGroup row>
          <Field
            id="symbol"
            name="symbol"
            type="text"
            component={inputField}
            placeholder="Enter Product Here"
          />
          <Field id="side" name="side" component={inputField} type="select">
            <option value={null}>Any</option>
            <option value="Buy">Buy</option>
            <option value="Sell">Sell</option>
          </Field>
          <Field id="status" name="status" component={inputField} type="select">
            <option value={null}>Any</option>
            <option value="Working">Working</option>
            <option value="Completed">Completed</option>
          </Field>
          <Button name="submit-btn" className="filter-submit-btn" color="danger" type="submit">
        Submit
      </Button>
    </FormGroup>
  </Form>

我添加了一个类名标签,但我发现我添加的占位符和类名都没有显示。如何自定义每个字段?

<Field 
    type="text" 
    className="myClass"
    component={InputField} 
    placeholder="Type here..."
/>

您的自定义 InputField 应该类似于

(我从 http://redux-form.com/6.5.0/examples/submitValidation/ 中获取了这个例子)

export const InputField = ({ input, type, placeholder, className, meta: { touched, error } }) => (
  <div>
      <input {...input} placeholder={placeholder} type={type} className={className}/>
      {meta.touched && meta.error && <span>{meta.error}</span>}
  </div>
)

或者更好的方法,如果props太多,可以用object destructuring

export const InputField = (field) => ( 
    <div> 
        <input {...field.input} {...field} /> 
        {field.meta.touched && field.meta.error && <span className="error">{field.meta.error}</span>} 
    </div>
)

{...field} 将提取您在 Field 中传递的所有道具。

您可以查看这个官方 redux-form 示例:http://redux-form.com/6.5.0/examples/react-widgets/ 以获得更多想法。

希望对您有所帮助:)

You can use object destructuring method to set className.

<Field 
        type="text" 
        input={{className:'red'}}
        component={InputField} 
        placeholder="Type here..."
    />

我知道您说 component={InputField} 时使用的是自定义渲染器,但对于来到这里的其他人(因为我在文档中找不到它):如果您使用的是内置渲染器之一component="input"component="select" 等渲染器,您只需添加 className 渲染器就会应用它,例如:

<Field name="foo" component="select" className="form-control">
</Field>

根据定义,您传递给 Field 组件的任何内容都应作为 input 属性传递给 InputField 组件。因此,您的 InputField 组件应如下所示:

<div> 
    <InputField  {...field.input} > {field.children} </InputField> 
    {field.meta.touched && field.meta.error && <span className="error"> 
    {field.meta.error}</span>}
</div>