导出变量-React



我有一个名为Component1的组件,其中有以下代码:

import React, { useState } from "react";
import Popover from "material-ui-popup-state/HoverPopover";
import Fab from "@material-ui/core/Fab";
import {
usePopupState,
bindHover,
bindPopover
} from "material-ui-popup-state/hooks";
import PaletteIcon from "@material-ui/icons/Palette";
import Colors from "./Colors";
const DEFAULT_COLOR = "red";
const COLORS = [/*list of colors*/];
const Component1 = ({ classes }) => {
const popupState = usePopupState({
variant: "popover",
popupId: "demoPopover"
});
const [selectedColor, setSelectedColor] = useState(DEFAULT_COLOR);
return (
<div className="box" style={{ backgroundColor: selectedColor }}>
<Fab variant="extended" {...bindHover(popupState)}>
<PaletteIcon />
</Fab>
<Popover
>
<div className="color-palette">
{COLORS.map((color) => (
<Colors
key={color}
selected={selectedColor === color}
onClick={setSelectedColor}
color={color}
/>
))}
</div>
</Popover>
</div>
);
};
export default Component1;

该组件在Component2中导入,其中代码为:

import React from "react";
import Component1 from "./Component1";
import Fab from "@material-ui/core/Fab";
import DeleteIcon from "@material-ui/icons/Delete";
function Component2(props) {
function handleClick() {
props.onDelete(props.id);
}
return (
<div className="note" style={{ backgroundColor: "selectedColor" }}>
<h1>{props.title}</h1>
<p>{props.content}</p>
<Fab onClick={handleClick}>
<DeleteIcon fontSize="small" />
</Fab>
<HoverPopover />
</div>
);
}
export default Component2;

在组件2中,我需要将const selectedColor用于divclass="note"的样式设置。然而,问题是当我从COLORS列表中选择颜色时,divclass="note"的背景色不会改变。我尝试了很多选择,但我不知道如何正确地做。请告诉我怎样做对。

共享;selectedColor;变量,它实际上是一个状态,您必须将它通过props传递给子组件

您的";组件2";应声明状态";selectedColor";,并且该状态及其功能必须由道具传递给您的";组件1";。

https://reactjs.org/tutorial/tutorial.html#lifting-状态启动

最新更新