单击按钮时更改按钮样式

41

onClick函数中更改按钮的background-color是否可能?

例如,点击background-color: black,再次点击background-color: white

我尝试了像this.style这样的东西,但没有结果。

我成功地让叠加层工作并将所需数据插入其中。但是我没有找到任何可以帮助我的帖子。我正在使用react-bootstrap。这是我的代码。

  const metaDataOverlay = (
  <div>
  <style type="text/css">{`
  .btn-overlay {
    background-color: white;
    margin-right: -15px;
    margin-left: -15px;
    padding-bottom: -20px;
    padding: 0;
  }
  `}</style>

      <ButtonToolbar>
        <ButtonGroup>
        <OverlayTrigger trigger={['hover', 'focus']} placement="left" overlay={popoverHoverFocus}>
          <Button bsStyle="overlay" onClick={ clicked } onKeyPress={ keypress }>
            <div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
              <a href={url} onClick={(e)=>{e.preventDefault(); console.log("123")}}>
                <div>
                  <img data-qa="poster" className={bemBlocks.item("poster")} src={result._source.poster} width="240" height="240"/>
                </div>
              </a>
            </div>
          </Button>
        </OverlayTrigger>
        </ButtonGroup>
      </ButtonToolbar>

    </div>
  )
6个回答

55

你可以尝试使用状态来存储颜色。也许这能给你解决问题的思路:

class Test extends React.Component {
    constructor(){
        super();

        this.state = {
           black: true
        }
    }

    changeColor(){
       this.setState({black: !this.state.black})
    }

    render(){
        let btn_class = this.state.black ? "blackButton" : "whiteButton";

        return (
             <button className={btn_class} onClick={this.changeColor.bind(this)}>
                  Button
             </button>
        )
    }
}

React.render(<Test />, document.getElementById('container'));

这里有一个 JSFiddle。


1
是的,它确实有帮助。我还发现这个链接很有用,因为它提供了示例。 - user3350597
但是有了这个,你怎么让按钮在点击时除了改变颜色之外做其他事情呢?比如说你想要触发一个函数... - mrpbennett

35

您还可以访问事件和当前事件的目标。

handleClick = (event) => {
   // accessible
   event.target.style
   event.target.classList //to change style via css
}

你能用黑白完成这个吗? - kirill_igum
3
event.target.style.backgroundColor = "red" 可翻译为:事件目标的样式设置为红色背景色e.target.classList.add("mystyle"); 可翻译为:事件目标的类列表添加了“mystyle”类 - Nevada

3

这里有另一个解决方案

changeStyles = () => {
    let element = document.getElementById('button')
    ReactDOM.findDOMNode(element).style.backgroundColor = this.state.isClicked?'black' : 'white'
}

通过这种方式,您可以仅更改所需的样式属性,从而防止在 CSS 中出现重复。


2

这是您可以访问的方式

    handleClick=(e)=>{
        console.log("this is working fine");
        e.preventDefault();
        e.target.style.color = 'black'
        console.log(e.target);
    }

如果您希望实现更多的动态效果,可以事先使用某些默认的样式值来初始化状态,然后使用 setState 函数来更新状态。更多内容请参考使用状态的正确方式

0

这里有另一种解决方案:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
      BackgroundColor: "BLACK"};
  };

render(){
    return (
      <div className='app'>
        <button className={this.state.BackgroundColor === "BLACK" ? "Black" : "nothing"}
        onClick={() => {this.setState({BackgroundColor: "WHITE"})}}>CHANGE TO BLACK</button>
        <button className={this.state.BackgroundColor === "WHITE" ? "White" : "nothing"}
        onClick={() => {this.setState({BackgroundColor: "BLACK"})}}>CHANGE TO WHITE</button>
      </div>
    );
  }
}

export default App;

这段代码将帮助您隐藏原来的黑色按钮,并用白色背景的新按钮替换它。此功能还适用于新的白色按钮。如果您只想更改按钮的背景颜色而不重复情况,您也可以尝试在渲染中更改条件状态。
render(){
    return (
      <div className='app'>
        <button className={this.state.BackgroundColor === "BLACK" ? "Black" : "White"}
        onClick={() => {this.setState({BackgroundColor: "WHITE"})}}>CHANGE TO BLACK</button>
      </div>
    );
  }
}

这是 CSS 代码:
*{
  margin: 0;
  padding: 0;
 }

.app{
  display: flex;
  justify-content: center;
  align-items: center;
}
.Black{
  background-color: black;
  color: white;
}

.White{
  background-color: white;
  color: black;
}

.nothing{
  display: none;
}

0
将此添加到您的工具提示中。
<Tooltip cursor={{ fill: 'transparent' }} />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接