我想在地图内创建条件渲染。数据取自具有以下结构的 JSON 文件:
export const products = [
{
"scores": {
"quality": 8,
"relevancy": {
"design": 3,
"code": 9,
"business": 5
}
},
"title": "AdCall: Bringing WebRTC to display ads",
"subtitle": "The first advertising banner with video calls",
"content": [
{
"type": "text",
"body": "AdCall is a concept for a new kind of online advertising banner. Using WebRTC, it allows for a click to call action with the aim of increasing conversions. It's built with a Node backend and deployed on Heroku."
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
所以我通过数组创建了一个地图,然后我想根据类型来呈现内容部分。我为此使用了双地图,我需要在第二张地图中使用条件,但它不起作用:
return (
<div className="LongWork">
{products.map((product, i) => {
<div className="product-wrapper" key={i}>
<div className="subtitle"><span className="subtitle-span">{product.subtitle}</span></div>
<div className="title">{product.title}</div>
{product.content.map((content, l) => {
<div className="product-content" key={l}>
{if (content.type==="text") {
return (
<div className="productText">
{content.body}
</div>
)}
}}
</div>
})}
</div>
}
)
Run Code Online (Sandbox Code Playgroud)
使用ternary operator
有条件的渲染,因为if-else
我们不能使用里面JSX
。
另一个问题是,您没有返回map
body内的任何内容,因此return
也使用返回元素。
为什么我们不能在 JSX 中使用 if-else?
检查此答案以获取解释:jsx 中的 if-else 语句:ReactJS
像这样写:
<div className="LongWork">
{products.map((product, i) => {
return (
<div className="product-wrapper" key={i}>
<div className="subtitle"><span className="subtitle-span">{product.subtitle}</span></div>
<div className="title">{product.title}</div>
{product.content.map((content, l) => {
return(
<div className="product-content" key={l}>
{content.type === "text" ?
<div className="productText">
{content.body}
</div>
: null}
</div>
)
})}
</div>
)
})}
</div>
Run Code Online (Sandbox Code Playgroud)
更新:
使用危险的SetInnerHTML来呈现 html 字符串。
检查这个片段:
<div className="LongWork">
{products.map((product, i) => {
return (
<div className="product-wrapper" key={i}>
<div className="subtitle"><span className="subtitle-span">{product.subtitle}</span></div>
<div className="title">{product.title}</div>
{product.content.map((content, l) => {
return(
<div className="product-content" key={l}>
{content.type === "text" ?
<div className="productText">
{content.body}
</div>
: null}
</div>
)
})}
</div>
)
})}
</div>
Run Code Online (Sandbox Code Playgroud)
let str = "<div>Hello Ocram</div>"
let App = () => {
return(
<div>
<div dangerouslySetInnerHTML={{ __html: str }}></div>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7252 次 |
最近记录: |