React中如何结合const样式与内联硬编码样式?
Hey there! The problem with your current code is that you can’t just nest style objects like style{width: "20%"} in React’s style prop — React expects a single valid object here. You need to merge your pre-defined style constant with the additional inline styles instead. Here are two simple, common ways to do this:
1. Use the ES6 Object Spread Operator (Recommended)
This is the cleanest and most widely used approach in modern React. The spread operator (...) lets you "copy" all properties from your base style object, then add or override properties right after:
const style = { cursor: "pointer", border: "2px solid #b1b1b1", borderRadius: "8px", padding: "0px 10px 0px 10px", backgroundColor: "green" }; // Merge base style with inline width <div style={{...style, width: "20%"}}>test</div>
Note: If your base style object ever includes a width property later, the inline width: "20%" will override it (since later properties in the object take precedence).
2. Use Object.assign()
If you need to support older environments without ES6 spread support, Object.assign() works too. Just make sure to pass an empty object as the first argument so you don’t mutate your original style constant:
<div style={Object.assign({}, style, {width: "20%"})}>test</div>
Here, Object.assign() creates a new object, copies all properties from style into it, then adds the width property from your inline object.
Either method will work perfectly for your use case — the spread operator is just more readable for most folks!
内容的提问来源于stack exchange,提问作者pat

