【问题标题】:React jsx style tag not applied to tags returned by functionsReact jsx样式标签不适用于函数返回的标签
【发布时间】:2021-01-25 18:15:54
【问题描述】:

我正在尝试将样式应用于从函数内部的 for 循环生成的标签。问题是标签中的样式不适用于这些生成的标签。可能是因为它们是在应用样式后生成的?我不知道。这是一个例子:

generateTags = (size) => {
    let tags = []
    for (var i = 0; i < size; i++) {
        tags.push(<img className="image-tag" src={this.state.imagePath} alt="image" key={Math.random() * Math.floor(100000)}/>)
    }
    return tags
}

render() {
    return (
        <div className="main">
            <div className="left-container">
                {this.generateTags(10)}
            </div>
        <style jsx> {`
            .main { <-- This is properly applied
                position: relative;
                width: 100%;
                height: 100%;
            }
            .image-tag { <-- This doesn't work
                position: absolute;
                width: 50px;
            }
        `} </style>
        </div>
    )
}

宽度:50px 不适用于图像,我放置的任何内容都没有任何区别。但是当我像这样在标签中添加样式时:

<img className="image-tag" style={{width: "50px"}} src={this.state.imagePath} alt="image" key={Math.random() * Math.floor(100000)}/>

然后正确应用样式。这是否意味着如果元素是从函数返回的,我不能在样式标签中包含 css?

【问题讨论】:

  • 您能否验证样式标签及其内容确实在输出页面上正确呈现?
  • 为什么不将样式内联到主 div 和 img 标签
  • @Sujit.Warrier 我发现将通常格式的样式很好地嵌套在文件末尾会更具可读性。样式标签还确保样式不会应用于其他组件中存在的相同类名。
  • @NikosM。该样式仅在标签本身内联时应用。我立刻注意到了一个机会。当样式在 jsx 样式标签内时,没有效果。

标签: css reactjs jsx


【解决方案1】:

您似乎正在使用Styled JSX。 Styled JSX 的原则之一是 CSS 是特定于组件的。由于您的 &lt;img&gt; 标签是在定义样式的 render() 函数之外创建的,因此不会应用它们。

在这种情况下,我建议使用 GenerateTags React 组件,而不是函数。这样,您可以根据需要生成标签,以及应用特定于组件的样式,如下所示:

GenerateTags = (props) => {
    const {size} = props

    let tags = []

    for (var i = 0; i < size; i++) {
        tags.push(i)
    }

    return(
        <>
            {tags.map((tag, index) => (
                <img className="image-tag" src={this.state.imagePath} alt="image" key={Math.random() * Math.floor(100000)}/>
            ))}

            <style jsx>{`
                // This will now work as it is in the same scope as the component
                .image-tag {
                    position: absolute;
                    width: 50px;
                }
            `}</style>
        </>
    )

    return tags
}

render() {
    return (
        <div className="main">
            <div className="left-container">
                <GenerateTags size={10} />
            </div>
        <style jsx> {`
            .main { <-- This is properly applied
                position: relative;
                width: 100%;
                height: 100%;
            }
        `} </style>
        </div>
    )
}

否则,如果您希望在组件范围之外应用这些样式,您可以使用global 选项:

<style jsx global>
  ...
</style>

【讨论】:

  • 我忘记了全局样式。看起来这是我正在尝试做的最好的解决方法,而且效果很好。谢谢!
猜你喜欢
  • 2016-06-22
  • 2015-02-16
  • 2017-04-13
  • 1970-01-01
  • 2019-12-17
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多