简体   繁体   中英

Trying to toggle the background color of a table row on hover using React, but nothing happens

My table row looks like this:

<tr
    onMouseEnter={() => {this.buttonIsHovered = true} }
    onMouseLeave={() => {this.buttonIsHovered = false}}
    className={this.buttonIsHovered ? 'hover' : null}>

buttonIsHovered starts out defined as false. Now, the CSS .hover class is defined like so:

.hover {
  background-color: aqua
}

I am sure that the CSS is successfully being imported. I have no clue why it doesn't work. Any suggestions are appreciated, thanks!

Here's an example of what you want:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    red: false
  };

  toggle = () => {
    this.setState({ red: !this.state.red });
  };

  render() {
    return (
      <React.Fragment>
        <h1
          onMouseEnter={this.toggle}
          onMouseLeave={this.toggle}
          style={{ background: this.state.red ? "red" : "" }}
        >
          Hover me!
        </h1>
      </React.Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox here .

You can change color by css style:

const styles = theme => ({ 
 button: {
  margin: '15px 0',
  color: '#fff',
  borderRadius: '5px',
  backgroundColor: '#fff',
  '&:hover': {
    backgroundColor: '#999',
  },
 },
})

Hello I just tested with this code and it worked

    class App extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      color: 'white'
    }
    this.changeColor = this.changeColor.bind(this);
    this.resetColor = this.resetColor.bind(this);
  }

  changeColor(){
    this.setState({color:'red'})
  }

  resetColor(){
    this.setState({color:'white'})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <table>
            <tbody>
              <tr onMouseEnter={this.changeColor} onMouseLeave={this.resetColor} style={{backgroundColor:this.state.color}}><td>shiiiiiiiiiiiiiiiiiiiiittttt</td></tr>
            </tbody>
          </table>
        </header>
      </div>
    );
  }
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM