如果其他条件不评估反应成分

时间:2020-02-17 18:01:24

标签: javascript reactjs jsx

因此,我正在制作待办事项列表应用程序,并为新待办事项添加颜色,因为它们已添加到待办事项列表中,我已经在React组件中使用了if else语句,但我认为它没有进行评估。

下面是我正在使用的css文件中的两个类->

[
    {
        "id": 1,
        "shape": "triangle",
        "color": "red",
        "area": 5,
        "label": "T1"
    },
    {
        "id": 2,
        "shape": "triangle",
        "color": "green",
        "area": 27,
        "label": "T2"
    },
...

下面是从todolist->

接受参数item(待添加到列表中的待办事项)和key(作为键传递的索引)的组件。
 .bgColorItem1{
    background-color: white;
}

.bgColorItem2{
    background-color:grey;
}

所以我从这段代码中期望的是键,它是上面在todolist组件中传递给todo的索引,因此应该返回0,以便settingClass可以具有替代值并因此提供替代颜色。但是事实并非如此。

4 个答案:

答案 0 :(得分:1)

首先,请不要使用key的值,因为它是内部值。其次,您可以实现这样的目标

{items.map((item, index) => <TodoItem item={item} index={index} />)}

TodoItem

const TodoItem=({ item, index })=>{
        let settingClass=index % 2 === 0 ? 'bgColorItem1' : 'bgColorItem2';
    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}</div>
}

但是,您不需要做出任何反应,只需在CSS中使用CSS

.boxSpace:nth-child(odd) {
  background: red;
}

.boxSpace:nth-child(even) {
  background: blue;
}

答案 1 :(得分:0)

您不能使用key属性,因为它是保留的also you will get a warning for it

警告:ListItem:key不是道具。尝试访问它会导致返回undefined。如果需要在子组件中访问相同的值,则应将其作为其他属性传递。

简单的例子:

const ListItem = ({ key }) => {
  console.log(key);
  return <div>{key}</div>;
};

const App = () => {
  return (
    <>
      {[0, 1, 2, 4].map(item => (
        <ListItem key={item} />
      ))}
    </>
  );
};

Edit morning-mountain-quqor

答案 2 :(得分:0)

您的TodoItem组件不必在乎关键道具,而应该在意布尔值(如果有两种以上样式,则为字符串)道具,例如alternateStyle:

const TodoItem=({item,alternateStyle})=>{
    return <div className={
                 `boxSpace centerAligning ${alternateStyle ? 'bgColorItem2' : 
                 'bgColorItem1'}`
           }>
             {item}
           </div>

然后,您可以在父组件中设置您需要AlternateStyle的值:

<div>
   {items.map((item, index) => <TodoItem item={item} alternateStyle={index % 2 !== 0} />)}
</div>

答案 3 :(得分:-2)

键“ prop”在React中保留。您不能使用它。将该道具重命名为“ idx” 参见:Special props

相关问题