【发布时间】:2019-10-04 03:48:47
【问题描述】:
我正在迭代一个 JSX 代码块,该代码块从 json 文件中获取数据,并显示到 DOM。我需要在我的 map 函数的第一次迭代中应用一种样式,但其余部分需要为空白。
训练变量保存我的 json 文件中的数据。我需要在这个 map 方法的第一次迭代中应用“marginRight:'5%'”的样式。
trainer.js
{ training.map((course, index) => {
return (
<Course name={course.name}
school={course.school}
location={course.location}
year={course.year}
class={classes}
key={index}
style={{marginRight: '5%'}} <- this works but applies the style to all courses, which is not what I want.
/>
)
})}
trainerTemplate.js - 这是被渲染的模板。道具从 trainer.js 传递到这里
function Course(props){
return (
<Fragment>
<Grid item style={props.style}>
我假设我需要在某处设置一个三元运算符来检查索引是否为 0,但我似乎无法正常工作
【问题讨论】:
-
你试过
{{index === 0 ? marginRight: '5%' : ''}}- 你有索引,所以你知道什么时候你在0。使用它。 (伪代码。您可能需要重新安排一下才能完成这项工作,但这是您在 JSX 中比较的方式)
标签: reactjs material-ui ternary-operator