代码顶部的React内部CSS样式

时间:2019-02-22 00:38:11

标签: css reactjs

我正在尝试在React应用程序中设计组件的样式,但是我不想创建外部样式表,因为它是一个小项目。如何在不使用外部样式表的情况下为该图像组件设置样式?

return (
  <div>
    <Image>
      <div>
        <img src='./resources/image.png alt='image'>
      </div>
    </Image>
  </div>
);

我已经在网上找到了用于在特定元素上使用内联样式的资源,但是我想通过将代码放在组件的顶部来使代码整洁,就像在HTML文件的顶部使用样式标签一样。我没能在React中找到类似的东西。

4 个答案:

答案 0 :(得分:2)

对于内联样式,可以在文件顶部或在render方法中定义样式对象,然后引用它:

<div class="parent">
  <ol>
    <li>Topic</li>
    <ol>
      <li> Sub Topic 1 </li>
      <li> Sub Topic 2 </li>
    </ol>
    <li>Topic 2</li>
  </ol>
</div>

文档中的更多信息:https://reactjs.org/docs/dom-elements.html#style

答案 1 :(得分:0)

您可以执行以下操作:

const Image = styled.div`
      background: #1d9ac2;

      img {
          border: 1px solid red;
      }
`;

答案 2 :(得分:0)

有多种解决方案,关于哪个是“最佳”的争论很大。 我不知道哪个是最好的,但是我可以告诉你我使用的是哪个:

样式化的组件(https://www.styled-components.com/

以此,您将定义一个这样的对象

let styled = require('styled-components');
// Or for fancy people
import styled from 'styled-components';

const Image = styled.div`
  background-color: red;

  /* You can even put classes or selectors in here that will match the sub-components */
  .some_class_used_inside { color: black; }
  img { width: 100px }
`

并像这样使用它

return (
  <div>
    <Image> {/* This will be the `<div>` with `background-color: red` */}
      <div className="some_class_used_inside"> {/* This will now have `color: black` applied */
        <img src='./resources/image.png alt='image'> {/* This will have `width: 100px` applied to it */}
      </div>
    </Image>
  </div>
);

当然,还有很多其他的库可以做到这一点,我想每个人都必须找到自己喜欢的:)

答案 3 :(得分:0)

JSX中的内部CSS样式与HTML中的样式非常相似。唯一的区别是,您需要将样式名称声明为变量,因为它们像JS对象一样被对待。考虑到这一点,您还需要在每个属性的后面加上逗号而不是分号,并且最后一个属性的末尾应没有标点符号。使用这种方法,您还应该使用style={}而不是className={}。您可以阅读有关JSX样式here的更多信息。

const myStyle = {
    width: '300px',
    height: '300px',
    border: '2px solid black'
}

const Image = () => {
    return (
        <div>
            <img style={myStyle} src='./resources/image.png alt='image'>
        </div>
    );
}