【问题标题】:React JS react-bootstrap PopOver change the background-color for different button using classNameReact JS react-bootstrap PopOver 使用 className 更改不同按钮的背景颜色
【发布时间】:2020-05-02 08:56:38
【问题描述】:

我有一个 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';
}

【问题讨论】:

    标签: css reactjs twitter-bootstrap


    【解决方案1】:

    你可以这样做:

    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

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 1970-01-01
      • 2021-03-21
      • 2021-06-11
      • 2018-11-30
      • 2023-03-14
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多