如何使用内部有条件语句的map函数迭代对象数组


const images = [
{
url: 'https://source.unsplash.com/random/1000x671',
text: 'hi'
},
{
url: 'https://source.unsplash.com/random/1000x671',
text: 'hello'
},
]
const Test = () => {
const [on, toggle] = useState(false);
return (
<div>
{images.map((image, index) => (
<div key={index} onClick={() => toggle(!on)}>
{on && (
{image.text}
)}
<img src={image.url} />
</div>
)}
</div>
)
};
export default Test;

我正在使img url正确呈现,但img文本只显示数组中的第一个对象,唯一的区别似乎是因为它在条件语句中?任何可能导致这个问题的想法。谢谢大家!

您的jsx无效,这是您帖子中的拼写错误吗?代码中不存在该错误(请注意,您有3个打开的<div>s,但只有2个关闭的</div>s(?现在我只是假设这就是问题所在,试着把它改为:

<div>
{images.map((image, index) => (
<div key={index} onClick={() => toggle(!on)}>
{on && <div>{image.text}</div> }
<img src={image.url} />
</div>
)}
</div>

问题来自于用于有条件呈现标题的语法。

{on && ({image.text})}

它应该只是{on && image.text},除非您需要用另一个元素(如h1{on && <h1>{image.text}</h1>}(来包装它。

const {useState, useEffect} = React;
const images = [
{
url: 'https://source.unsplash.com/random/1000x671',
text: 'hi'
},
{
url: 'https://source.unsplash.com/random/1000x671',
text: 'hello'
}
];
const Test = () => {
const [on, toggle] = useState(false);
return (
<div>
{images.map((image, index) => (
<div key={index} onClick={() => toggle(!on)}>
{on && image.text}
<img src={image.url} />
</div>
))}
</div>
)
};
ReactDOM.render(<Test />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

最新更新