React Component内联样式速记声明互相覆盖

时间:2017-07-11 13:47:57

标签: javascript css reactjs

我有一个React组件,它传递的值对象如下:

this.cell.style.setProperty('grid-area', values.gridArea);
this.cell.style.setProperty('grid-column', values.gridColumn);
this.cell.style.setProperty('grid-row', values.gridRow);

然后添加到组件的样式,如:

for (let prop in values) {
  this.cell.style[prop] = values[prop];
};

但是,使用网格列和网格行属性,这些属性缩写为'网格区域的简写声明:2/1/5/3'在浏览器中并覆盖我的网格区域样式。

如果我将其设置为循环,也会发生这种情况:

.ts

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

来自MDN:

  • grid-areagrid-row-startgrid-column-startgrid-row-endgrid-column-end
  • 的简写
  • grid-columngrid-column-startgrid-column-end
  • 的简写
  • grid-rowgrid-row-startgrid-row-end的缩写。

因此grid-areagrid-columngrid-row互斥。  React不是为了智能地为你合并这些CSS属性而设计的,它只是让最后一个定义为win。

但是,您可以添加逻辑以自行合并这些属性:

  const mergedGridColumn = gridColumn.replace(/[0-9*]/g, value => `${value} ${gridArea}`);
  const mergedGridRow = gridRow.replace(/[0-9*]/g, value => `${value} ${gridArea}`);

values

{
  const values = {
  gridArea: 'header',
  gridColumn: '1 / 3',
  gridRow: '2 / 5',
}

这会产生style

{
  grid-area: 2 header / 1 header / 5 header / 3 header;
}

以下完整示例:



const App = () => {
  const values = {
    gridArea: 'header',
    gridColumn: '1 / 3',
    gridRow: '2 / 5',
  };

  return (
    <div className="App" style={{display: 'grid'}}>
      <Header values={values} />
    </div>
  );
}

const Header = (props) => {
  const { gridArea, gridColumn, gridRow } = props.values;

  const mergedGridColumn = gridColumn.replace(/[0-9*]/g, value => `${value} ${gridArea}`);
  const mergedGridRow = gridRow.replace(/[0-9*]/g, value => `${value} ${gridArea}`);
  return (
    <div
      className="App-header"
      style={{
        gridColumn: mergedGridColumn,
        gridRow: mergedGridRow,
      }}
      >
      <h2>Welcome to React</h2>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
&#13;
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

.App {
  text-align: center;
}

.App-header {
  background-color: orchid;
  color: white
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
&#13;
&#13;
&#13;