redux-form语法疑问:扩展运算符用法及报错原因咨询
Hey there! I totally get the confusion around this syntax—redux-form's field object can feel a bit opaque at first. Let's break down your two questions clearly:
1. How does the spread operator work in the input tag?
First, let's recall what field.input is: redux-form passes a field object to your render function, and the input property inside it is an object containing all the standard form control props you'd normally pass to an input—things like value, onChange, onBlur, name, and more.
Using the spread operator ({...field.input}) is a shorthand way to pass all those props to the input tag at once, instead of writing them out individually. So instead of:
<input value={field.input.value} onChange={field.input.onChange} onBlur={field.input.onBlur} name={field.input.name} type="text" />
You can write the much cleaner:
<input {...field.input} type="text"/>
This automatically applies all the necessary props that redux-form needs to track and update the form state.
2. Why does <input {...field.input, id} type="text"/> throw an error?
The issue here is likely one of two common problems:
a) The id variable isn't defined
If you're using the shorthand id (instead of id: someValue), JavaScript expects there to be a variable named id in scope that holds the value you want to assign to the input's id attribute. If id hasn't been declared anywhere, you'll get a ReferenceError saying the variable is undefined.
b) Missing explicit key-value syntax
If you meant to set a specific id value directly (without a variable), you need to use the full key-value pair syntax. For example, to set an id of "username-field", you should write:
<input {...field.input, id: "username-field"} type="text"/>
The shorthand id only works when you have a variable with the exact same name as the attribute. So if you declare:
const id = "username-field"; <input {...field.input, id} type="text"/>
This is valid (and equivalent to the line above) because JavaScript interprets it as id: id.
One quick note: if field.input already has an id property, the id you add after the spread operator will override it—later properties in the object literal take precedence over earlier ones.
To fix your error, either define the id variable before using it, or use the explicit id: yourValue syntax.
内容的提问来源于stack exchange,提问作者Poogy

