css - React JS react-bootstrap PopOver 使用 className 更改不同按钮的背景颜色
问题描述
我有一个 react js 组件,它有许多按钮,可以显示不同的弹出框,也就是工具提示消息。我需要为每个弹出框标题应用不同的背景颜色。我在 css 文件和 jsx 代码中添加了颜色,每个弹出框调用一个函数来获取适当的背景颜色样式。到目前为止,着色不起作用。我在这里看到其他人使用 css 中的 .popover-titles 但这会使所有弹出窗口的颜色相同。我需要为每个按钮应用不同的颜色。
任何帮助表示赞赏。谢谢
从“cssFile”导入样式
CSS
:local .greenColor
background-color: F990099
color: #000000
JSX code
<Popover id="1" title="test title" className={this.getBackgroundColor()}>test</Popover>
// I have many of these Popover element. I like to call the getBackgroundColor function to get a specific styling
getBackgroundColor = () => {
return 'styles.greenColor';
}
解决方案
你可以这样做:
import React from "react";
import ReactDOM from "react-dom";
import Popover from "react-popover";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { id: -1, color: "white", isOpen: false };
}
togglePopover = (e, _id, _color) => {
if (_id !== this.state.id && this.state.isOpen) {
this.setState({ isOpen: !this.state.isOpen }, function() {
this.setState({ id: _id, color: _color, isOpen: !this.state.isOpen });
});
} else
this.setState({ id: _id, color: _color, isOpen: !this.state.isOpen });
};
render() {
return (
<div className="App" style={{ margin: "50px" }}>
<div>
<Popover
style={{ backgroundColor: this.state.color, color: "white" }}
isOpen={this.state.isOpen && this.state.id === 1}
body={<div className="Balloon">Popover Content</div>}
>
<button onClick={e => this.togglePopover(e, 1, "red")}>
Toggle Popover
</button>
</Popover>
</div>
<br />
<br />
<div>
<Popover
style={{ backgroundColor: this.state.color }}
isOpen={this.state.isOpen && this.state.id === 2}
body={<div className="Balloon">Popover Content</div>}
>
<button onClick={e => this.togglePopover(e, 2, "yellow")}>
Toggle Popover
</button>
</Popover>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您也可以将togglePopover
函数用作鼠标悬停方法,它适用于任意数量,Popover
无需更改内部代码
答案输出:HERE
推荐阅读
- javascript - JavaScript解释器如何将全局语句添加到事件队列中?
- python - 在捕获并立即引发异常时避免“在处理上述异常期间,发生了另一个异常”
- javascript - 我怎样才能在这个里面放空格
- javascript - 使用 Express 和 Node 将 HTML、CSS 和 Javascript 连接到服务器
- python - 尝试创建一个 Discord webhook,并在代码中分配了头像和用户名
- python - Pandas:多对一合并
- php - PHP/Regex: Parse JSON in string
- highcharts - 使用带有 Highcharts 的 pickadate.js - 事件绑定问题
- c# - 在 Blazor Razor 页面中加载 AngularJS 页面/控制器
- xml - 将多个xml文件合并为一个大文件