将样式道具传播给React子级,并将其应用到CSS文件中



我正在渲染组件Dropdown,它的作用类似于html下拉组件,但它是div有序和无序列表的集合。我正试图将样式传递给className元素,这些元素具有呈现样式的dropdown.css文件,但我不确定如何从父组件一直针对这些特定元素。如何瞄准

div className="选择当前框";

style={{ border: "1px solid #D4D4D4" }}

div className="选择框列表";

使用

style={{
opacity: 1,
display: "inherit",
animationName: "none",
cursor: "pointer"
}}

CodeSandlox在这里->https://codesandbox.io/s/weathered-wood-cf8u8?file=/src/App.js:481-614

因此,使用React,如果您传递相同名称的道具,它只选择最后传递的道具。所以有了你的两个风格道具,它只会通过最后一个。然而,无论如何,使用名称样式可能不是最好的主意,因为它不是描述性的,而且还反映了实际的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.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>

我在沙盒中加入了一个工作示例。但是我没有设置的节点在DropdowView中使用className道具,因为不清楚哪个元素会有这个。

https://codesandbox.io/s/hardcore-sun-yyx0g?file=/src/DropdownView.jsx

我认为您可以直接将这些样式用于这些元素,而不是从父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

最新更新