似乎不能让这个工作:
只想在自己的行上显示每个音符项目
function EventsTimeline() {
const timelineEvents = [
{
date: 'January',
note: "Words words words"
},
{
date: 'March',
note: 'Scaling open maps for Jakarta flooding — and printed maps'
},
{
date: 'August',
note: 'more stuff ',
},
{
date: 'September',
note: ["Hurricane Harvey recovery maps", "dfdfdfff" ]
},
{
date: 'October',
note: 'Resdfsdfd dgdgdg'
},
{
date: 'November',
note: 'omus omus mos'
},
{
date: 'December',
note: 'rrrrrrs',
}
];
let eventPositionCount = -1;
let eventPositionClass,
eventDescription = null;
const eventElements = timelineEvents.map((event, i) => {
eventPositionCount++;
eventPositionClass = eventPositionCount % 2 === 0 ? 'even' : 'odd';
if (event.note[0].length !== 1 ) {
for (i = 0; i < event.note.length; i++) {
const a = event.note[i]
eventDescription = <p className="txt-s">{a}</p>;
}
} else {
eventDescription = <p className="txt-s">{event.note}</p>;
}
我尝试了很多不同的方法,但没有任何作用..我做错了什么?目前我甚至无法识别与数组相关的音符或日期
if (Array.isArray(event.note) == true ){
const a = event.note
a.map(function(item) {
eventDescription = {item}
})
} else {
eventDescription = <p className="txt-s">{event.note}</p>;
}
预期输出只是一个列表.. 九月
答案 0 :(得分:0)
代码现在的工作方式,它创建一个eventDescription
变量,然后在每个循环上反复将该变量重新设置为单个元素。相反,您需要将该变量作为元素的列表,而不仅仅是单个元素。这是你可以做的:
function EventsTimeline() {
const eventDescriptionElements = timelineEvents.map((event, i) => {
// here, if the note property isn't already an array, we'll make it one
// otherwise, we'll keep it as-is
// this makes it so that we can always use .map even if it's just one array value
const notes = Array.isArray(event.note) ? event.note : [event.note]
const noteElements = notes.map((noteText, i) => {
// key is required in array elements to silence the react warning
return <p key={i}>{noteText}</p>
})
return (
<p key={i} className="txt-s">
{noteElements}
</p>
)
})
return <div>{eventDescriptionElements}</div>
}
此外,对于偶数/奇数逻辑,你有:没有必要创建一个单独的eventPositionCount
变量,因为i
内的.map(...)
变量已经为你做了
eventPositionClass = i % 2 === 0 ? 'even' : 'odd';
答案 1 :(得分:0)
你应该尝试类似下面的内容
function eventsTimeLine() {
timelineEvent.map( event => {
<div>
<p>
{Array.isArray(event.note) ?
event.note.map( words => (
<span> words </span>
: <span> event.note </span>
}
</p>
</div>
});
}