Changing style of a button on click

后端 未结 5 810
执念已碎
执念已碎 2020-12-08 10:25

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

ex. click background-color: black, another click

相关标签:
5条回答
  • 2020-12-08 11:05

    This is how you can access

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

    If you want more dynamically you can initialize state with some default value of style afterwords use setState function to update your state

    0 讨论(0)
  • 2020-12-08 11:07

    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.

    0 讨论(0)
  • 2020-12-08 11:13

    Add this to your Tooltip

    <Tooltip cursor={{ fill: 'transparent' }} />
    
    0 讨论(0)
  • 2020-12-08 11:25

    Here is another solution

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

    In this way you can change only needed style property preventing duplicates in CSS.

    0 讨论(0)
  • 2020-12-08 11:28

    You also have access to event and current target of the event

    handleClick = (event) => {
       // accessible
       event.target.style
       event.target.classList //to change style via css
    }
    
    0 讨论(0)
提交回复
热议问题