【发布时间】:2020-06-01 17:18:06
【问题描述】:
所以我正在制作一个待办事项列表应用程序并为新的待办事项提供替代颜色,因为它们被添加到待办事项列表中,我在 React 组件中使用了 if else 语句,但我认为它没有评估。
以下是我正在使用的 css 文件中的两个类 -->
.bgColorItem1{
background-color: white;
}
.bgColorItem2{
background-color:grey;
}
下面是从todolist接受参数item(将添加到列表中的待办事项)和key(作为key传递的索引)的组件 -->
import React from 'react';
import './App.css';
const TodoItem=({item,key})=>{
let settingClass="";
// *****so the problem is here in the if condn that's not putting settingClass as bgColorItem1*****
if(key%2===0){
settingClass="bgColorItem1";
}else{
settingClass="bgColorItem2";
}
return <div className={`boxSpace centerAligning ${settingClass}`}>{item}</div>
}
export default TodoItem;
所以我期望从这段代码中,作为 todolist 组件索引的键在上面传递给 todo 应该返回 0,这样 settingClass 可以具有替代值并因此提供替代颜色。但事实并非如此。
【问题讨论】:
-
你是如何传递密钥的?不要使用 key 的值,使用 index/id 之类的东西
-
你不能使用
keyprop,它是保留的 -
keys 在 React 中有特殊的含义,不能简单地从组件的 props 中读取。考虑使用不同的术语。 reactjs.org/docs/lists-and-keys.html#keys -
settingClass仅存在于“TodoItem”函数中,您的值是“未定义”,您也没有在“TodoItem”函数中返回
标签: javascript reactjs jsx