React jsx样式的标记未应用于函数返回的标记



我正在尝试将样式应用于从函数内部的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?

看起来您正在使用样式化的JSX。样式化JSX的原则之一是CSS是特定于组件的。由于<img>标记是在定义样式的render()函数之外创建的,因此不会应用它们。

在这种情况下,我建议使用GenerateTagsReact组件,而不是函数。这样,您就可以根据需要生成标签,并应用组件特定的样式,比如:

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>

最新更新