问题
I've created a redux-form and i want to add className to each Field to customize them with css. The code for each field is:
<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>
I've added a className tag but i see that neither the placeholder i've added is shown nor the className. How can i customize each field?
回答1:
<Field
type="text"
className="myClass"
component={InputField}
placeholder="Type here..."
/>
and your custom InputField
should be something like
(I've taken this example from 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>
)
or a better approach, if too many props are there, You can use 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}
will extract all props that you have passed in Field
.
You can take a look at this official redux-form example: http://redux-form.com/6.5.0/examples/react-widgets/ to get more idea.
Hope it helps :)
回答2:
You can use object destructuring method to set className.
<Field
type="text"
input={{className:'red'}}
component={InputField}
placeholder="Type here..."
/>
回答3:
I realize that you are using a custom renderer by saying component={InputField}
, but for others coming here (since I can't find it in the docs): if you are using one of the built-in renderers like component="input"
or component="select"
, you can just add className
and the renderer will apply it, e.g.:
<Field name="foo" component="select" className="form-control">
</Field>
来源:https://stackoverflow.com/questions/42200542/classname-in-field-in-redux-form