【问题标题】:How to change style of an element in React without using querySelector?如何在不使用 querySelector 的情况下更改 React 中元素的样式?
【发布时间】:2020-12-31 14:29:07
【问题描述】:

我是 React 的新手。在这里,我试图根据条件覆盖类的 CSS

let customizeColumn = document.querySelector(".main-table-body");
!expandFilter ? customizeColumn.setAttribute("style", `height:calc(100vh - 345px)`) : customizeColumn.setAttribute("style", `height:calc(100vh - 302px)`);

在这里,我正在管理此变量的状态,并在按钮单击时调用 toggleFilter

const [expandFilter, toggleFilter] = useState(false);

但我不想使用document.querySelector(".main-table-body") 来获取课程,有没有其他方法可以做到这一点。我也在使用Material-UI。如果有帮助

【问题讨论】:

    标签: css reactjs material-ui


    【解决方案1】:

    main-table-body的渲染中,检查状态以确定它应该具有什么CSS属性,例如:

    return (
      <table 
        class="main-table-body"
        style={{ height: `calc(100vh - ${expandFilter ? 302 : 345}px)` }}
      >
        // table contents
      </table>
    );
    

    【讨论】:

      【解决方案2】:

      您可以使用 style 属性应用样式。

      在渲染方法中这样做

      const pixelsToReduce= expandFilter ? 302 : 345
      const height=`calc(100vh - pixelsToReduce)`
      return (
        <table
           class="main-table-body"
           style={{height:height}}
        >
        </table>
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        相关资源
        最近更新 更多