简体   繁体   English

如何在React.js中编辑多个元素的样式

[英]How to edit the styling of multple elements in React.js

Just finished my Codecademy react courses, and I'm still a bit fuzzy on some concepts like styling. 刚刚完成我的Codecademy反应课程,我对样式等某些概念仍然有些模糊。

Normally, if I had to style a list in css, it would look like: 通常,如果我必须在CSS中设置列表样式,则它看起来像:

li {
    text-decoration: none,
    color: 'white'
}

Now, if I had written that outside of the HTML sheet, and instead through JSX, I know that I can assign the styling to a variable like: 现在,如果我是在HTML工作表之外编写该代码的,而是通过JSX编写的,那么我知道可以将样式分配给一个变量,例如:

var linkStyle = {
    textDecoration: 'none',
    color: 'white'
}

And apply it to my elements like: 并将其应用于我的元素,例如:

<li style={listStyle}>Home</li>

However, this seems a bit redundant when I have multiple items in the list and need to apply the same style to all of them, as shown below: 但是,当列表中有多个项目并且需要对所有项目都应用相同的样式时,这似乎有点多余,如下所示:

render: function() {
        return (
            <div style={divStyle}>
                <ul>
                    <li style={listStyle}><a href='#' style={linkStyle}>Home</a></li>
                    <li style={listStyle}><a href='#' style={linkStyle}>About Us</a></li>
                    <li style={listStyle}><a href='#' style={linkStyle}>Contact Us</a></li>
                    <li style={listStyle}><a href='#' style={linkStyle}>Library</a></li>
                </ul>
            </div>
        );
    }  

How do I avoid this and apply the styles in a DRY way of thinking? 如何避免这种情况,并以一种DRY的思维方式应用样式?

If you want to use only inline styles , you can make the content as an array and call a map over it 如果只想使用inline styles ,则可以将内容设置为数组并在其上调用map

render: function() {
        return (
            <div style={divStyle}>
                <ul>
                 {
                  ['Home', 'About us', 'Contact Us', 'Library']
                  .map((el) =>
                    <li style={listStyle}>
                      <a href='#' style={linkStyle}>{el}</a>
                    </li>
                   )
                  }
                </ul>
            </div>
        );
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM