2 回答

TA貢獻1982條經驗 獲得超2個贊
因此,在 React 中,如果你傳遞同名的 props,它只會選擇最后傳遞的那個。因此,使用您的兩個樣式道具,它只會通過最后一個。然而,無論如何使用名稱樣式可能都不是最好的主意,因為它不是描述性的,而且還反映了實際的 HTML 樣式屬性。
在 App.js 文件中為兩種不同的樣式指定唯一的名稱:
<div className="App">
<Dropdown
inputName="viola"
list={[
{ yard_id: "1", yard_name: "Yard 1" },
{ yard_id: "2", yard_name: "Yard 2" }
]}
// this style is for className="select-box-current"
currentStyles={{ border: "1px solid #D4D4D4" }}
// this style is for className="select-box-list"
listStyles={{
opacity: 1,
display: "inherit",
animationName: "none",
cursor: "pointer"
}}
/>
</div>
現在我們需要通過組件樹傳遞這兩個屬性,下一個文件是 Dropdown.js 文件。
在我開始傳遞道具之前,我想對一些錯誤的、不完全相關的事情發表評論。
export const Dropdown = ({ list, ...others }) => {
const copiedProps = {};
Object.keys(others).forEach((key) => {
// these are the props that need to get thru:
if ("style" === key || "className" === key) {
copiedProps[key] = others[key];
}
});
...
復制道具是沒有必要的,而且復制的方式實際上是有害的。如果您想專門針對傳入 props 中的某個值,您可以直接訪問它(例如props.myProp或在本例中other.style)或解構賦值。
由于您只想傳遞樣式(現在為 listStyles 和 currentStyles)和 className,因此我選擇使用解構賦值將它們分配給變量。
export const Dropdown = ({
list,
currentStyles,
listStyles,
className,
...others
}) => { ... }
現在我們有了這些道具,我們希望將其傳遞到包含DropdownView您想要定位的實際元素的您的道具中。
<DropdownView
dropdownItems={dropdownItems}
activeItem={activeItem}
hover={hover}
setActiveItem={(activeItem) => {
setActiveItem(activeItem);
}}
onMouseOver={(hover) => onMouseOver(hover)}
toggleList={() => toggleList(!hideList)}
hideList={hideList}
className={className}
currentStyles={currentStyles}
listStyles={listStyles}
/>
好的,現在我們有了我們想要的樣式和類名。您所要做的就是像上面那樣獲取道具,然后將它們設置在元素上。
<div
className="select-box-current"
tabIndex="0"
autoFocus={true}
onClick={() => toggleList()}
style={currentStyles}
>...</div>
我分叉了沙箱以包含一個工作示例。但是我沒有在 中設置使用 className 屬性的節點,DropdowView因為不清楚哪個元素將具有該屬性。
https://codesandbox.io/s/hardcore-sun-yyx0g?file=/src/DropdownView.jsx

TA貢獻2019條經驗 獲得超9個贊
我認為您可以直接將這些樣式用于這些元素,而不是從父 div 中使用它們,如下所示。https://codesandbox.io/s/eloquent-lamport-3spzr?file=/src/App.js
但是如果你想使用父級的那些樣式。然后您可以使用特定名稱傳遞它們。像這樣
<Dropdown
inputName="viola"
list={[
{ yard_id: "1", yard_name: "Yard 1" },
{ yard_id: "2", yard_name: "Yard 2" }
]}
// this style is for className="select-box-current"
selectBoxCurrentStyle={{ border: "1px solid #D4D4D4" }}
// this style is for className="select-box-list"
selectBoxListStyle={{
opacity: 1,
display: "inherit",
animationName: "none",
cursor: "pointer"
}}
/>
這是鏈接https://codesandbox.io/s/damp-rain-cyhxb?file=/src/App.js:133-643
添加回答
舉報