如何在React中更改元素的样式?

kar*_*hna 5 javascript reactjs

我对Reactjs非常陌生,并且td在我的render方法中有一个:

<td style={{cursor: 'pointer'}} onClick={} key={i}>
Run Code Online (Sandbox Code Playgroud)

单击此按钮后td,我想更改其样式,如何在react js中执行此操作?

谢谢。

编辑:

这是我通过td以下方式生成的:

{this.props.posts.map((service, i) =>
     <tr>
        <td style={{cursor: 'pointer'}} key={i}>
           <span> {posts.createdBy} </span>
        </td>
     </tr>
)}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ams 5

当然假设所有其他鸭子都按顺序排列,您可以在组件状态中跟踪该类,然后在 onClick 事件中使用逻辑更新状态。

var TableData = React.createClass({
  getInitialState: function() {
    return {
      class: 'pointer'
    };
  },
  changeStyle: function(e) {
    if (this.state.class === 'pointer') {
      this.setState({class: 'not pointer'});
    } else {
      this.setState({class: 'pointer'});
    }
  },
  render: function() {
    return (
      <td style={ cursor: {this.state.class} }
          onClick={this.changeStyle}
          key={i}>
      </td>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)


sha*_*l01 5

对于现代反应:

您可以更改状态值

import { useState } from 'react';

const App = () => {

  const [ color, setColor ] = useState('#fff');
  const [ backgroundColor, setBackgroundColor ] = useState('#f44');

  return (
    <p style={{ 'color': color, 'backgroundColor': backgroundColor }} >
      Hello world
    </p>
  );
};

export default App;

Run Code Online (Sandbox Code Playgroud)

或者您可以在两个值之间切换

import { useState } from 'react';

const App = () => {

  const [ isFullWidth, setIsFullWidth ] = useState(false);

  return (
    <p style={{'width':` ${isFullWidth ? '100%' : '20%'}`}} >
      Hello world
    </p>
  );
};

export default App;


Run Code Online (Sandbox Code Playgroud)