【问题标题】:How to modify CSS using JavaScript in React.js如何在 React.js 中使用 JavaScript 修改 CSS
【发布时间】:2020-12-31 12:32:42
【问题描述】:

如何在 React 上使用 JavaScript 更改 css 样式?

例如,我会这样做:


document.querySelector('.container').style.backGroundColor='purple';

}

对吗?还是我应该用另一种方式来实现?

【问题讨论】:

  • 你在 React 中的 CSS 遵循了哪种方式?

标签: javascript html css reactjs frontend


【解决方案1】:

你可以使用 style 属性。

<SomeComponent style={{
    backgroundColor: someCondition ? 'purple' : null
}} />

【讨论】:

  • 避免像瘟疫一样的内联样式。在当时似乎是个好主意,但以后会变得很难维护
【解决方案2】:

考虑段落元素

document.getElementsByClassName("container").style.color = "blue";

【讨论】:

  • 这是一种非常必要的方式,与 React 相矛盾。
  • @StefanBajić 你能否详细说明它与 React 有何矛盾?
  • 我认为你的代码会在组件的下一次渲染后中断
【解决方案3】:

在 Reactjs 中更改 css 的简单方法是 Inline styling。其他方式可以查看:https://codeburst.io/4-four-ways-to-style-react-components-ac6f323da822

举个例子。如果您想更改用户状态的颜色。活动为绿色,非活动为红色。

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    const color = isActive ? 'green' : 'red';

    return <div style={{backgroundColor: color}}> {isActive ? 'Active' : 'Deactive'} </div>;
}

或者:

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    
    return <div style={{backgroundColor: isActive ? 'green' : 'red'}}> {isActive ? 'Active' : 'Deactive'} </div>;
}

或所有样式:

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    let styleStatus = isActive ?
        {
            backgroundColor: 'green',
            fontSize: '20',
        } :
        {
            backgroundColor: 'red',
            fontSize: '15',
        };

    return <div style={styleStatus}> {isActive ? 'Active' : 'Deactive'} </div>;
}

【讨论】:

    【解决方案4】:

    像这样创建一个 const 类型的 obj(必须在 render 方法中创建)

    const mystyle = {
          color: "white",
          backgroundColor: "DodgerBlue",
          padding: "10px",
          fontFamily: "Arial"
        };
    

    并像这样将其分配给您的元素

    h1 style={mystyle}>Hello Style!</h1>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 2016-11-14
      • 2018-09-17
      • 2017-02-16
      • 1970-01-01
      相关资源
      最近更新 更多