Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

reactjs - Changing style of a button on click

Is it possible to change background-color of my button onClick function?

ex. click background-color: black, another click background-color: white

I've tried something like this.style, no result.

I've managed to get overlay working and insert needed data inside of it. But didn't managed to find any post that could help me. I am using react-bootstrap. This is my code.

  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>
  )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try to use state to store the color. Maybe this would give you the idea how to solve the problem :

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'));

Here is a fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...