【问题标题】:Need help setting up a conditional in JSX需要帮助在 JSX 中设置条件
【发布时间】: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


【解决方案1】:

和@Kai Qing ansewr 一样

{ training.map((course, index) => {     
  return (
    <Course name={course.name}
        school={course.school}
        location={course.location}
        year={course.year}
        class={classes}
        key={index}
style={{marginRight: index === 0 ? '5%' : ''
  }}  
    />
  )
})}

【讨论】:

  • 差不多。您在marginRight 的值中有您的三元组,我敢打赌这是正确的方法。我不经常在 JSX 工作,所以我忘记了,但我很熟悉,知道它是这样的。
  • 默认值为0而不是空字符串会更好吗? marginRight: index === 0 ? marginRight: '5%' : '0'
  • {{marginRight: (index === 0 ? marginRight: '5%' : '0') }}怎么样
  • @Sung M. Kim 是的,但如果一个人正在使用另一个边距,那么它将覆盖它。
  • @learnerforlife 确保有两个右大括号:` style={{marginRight: index === 0 ? '5%' : ''}} `
【解决方案2】:

试试这个,我觉得比内联做起来要清楚一点:

{ training.map((course, index) => {
  const style = index === 0 ? { marginRight: '5%' } : null; // then use this as the style later
  return (
    <Course 
        name={course.name}
        school={course.school}
        location={course.location}
        year={course.year}
        className={classes} // also change this to className, not class
        key={index} // if you can, avoid using the index as the key
        style={style}  
    />
  )
})}

【讨论】:

    【解决方案3】:

    如果你有条件地想单独为第一项设置边距,你可以试试这个:这个传递第一个元素的样式属性,如果索引不属于第一个元素,则避免覆盖先前设置的边距。

    {training.map((course, index) => {
      return (
        <Course
          name={course.name}
          school={course.school}
          location={course.location}
          year={course.year}
          class={classes}
          key={index}
          style={index === 0 ? { marginRight: "5%" } : {}}
       />
      );
    })}
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2017-10-16
      相关资源
      最近更新 更多