根据React中的属性值映射不同的图标

时间:2018-12-11 15:16:26

标签: javascript reactjs lodash

https://codesandbox.io/s/r546o8v0kq

我上面的沙箱显示了一组项目的基本映射。这将根据项目的类型形成注释,日期和图标的列表。

我正在研究一些逻辑,该逻辑映射每个项目以找出其值,基于此,我为该值分配一个字符串以完成字体真棒徽标的类型。

const noteType = _.uniq(notes.map(value => value.intelType));
const noteIcon = [
  `${noteType}`.toUpperCase() == "EDUCATION"
    ? "paper-plane"
    : `${noteType}`.toUpperCase() == "ELIGIBILITY"
    ? "heart"
    : `${noteType}`.toUpperCase() == "GENERAL"
    ? "twitter"
    : null
];

如果“ intelType”的值为“ education”,它将返回“ paper-plane”字符串以完成图标。例如fa fa-${noteIcon}

    <List>
      {notes.map((note, index) =>
        note !== "" ? (
          <React.Fragment>
            <ListItem className="pl-0">
              <i class={`fa fa-${noteIcon}`} aria-hidden="true" />
              <ListItemText
                secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
              />
            </ListItem>
            <p>{note.note}</p>
            <Divider />
          </React.Fragment>
        ) : null
      )}
    </List>

它没有被映射并返回不符合任何条件的所有三个值,因此按要求返回null。我对下一步的工作感到有些困惑。

3 个答案:

答案 0 :(得分:1)

您可以定义一个将intel类型映射到图标名称的对象:

const noteIconMap = 
      { "EDUCATION": "paper-plane",
        "ELIGIBILITY": "heart",
        "GENERAL": "twitter",
      };

并在渲染器中以这种方式查找它:

<i class={`fa fa-${noteIconMap[note.intelType.toUpperCase()]}`} aria-hidden="true" />

尽管要注意,如果在note可以定义intelType的情况下,toUpperCase调用将引发错误。

以下是修改后的沙盒的链接: https://codesandbox.io/s/ojz2lzz03z

答案 1 :(得分:1)

我不确定这段代码是怎么回事:

const noteIcon = [
  `${noteType}`.toUpperCase() == "EDUCATION"
    ? "paper-plane"
    : `${noteType}`.toUpperCase() == "ELIGIBILITY"
    ? "heart"
    : `${noteType}`.toUpperCase() == "GENERAL"
    ? "twitter"
    : null
]

但是对我来说,将这些信息存储为对象,然后以这种方式访问​​图标类型更有意义。

const icons = {
    EDUCATION: 'paper-plane',
    ELIGIBILITY: 'heart',
    GENERAL: 'twitter'
}

然后继续:

icons[noteType]

答案 2 :(得分:0)

您需要在地图上为每个note.intelType获得一个图标。由于您要传递ID数组,因此不会匹配任何图标,并且结果始终为null

一个简单的解决方案是为图标(iconsMap)创建Map类型的图标,并使用note.intelType从地图中获取图标。

顺便说一句-当前note.intelType我们总是大写,因此您无需对其进行转换。

sandbox

const iconsMap = new Map([
  ['EDUCATION', 'paper-plane'],
  ['ELIGIBILITY', 'heart'],
  ['GENERAL', 'twitter'],
]);

class Notes extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { notes, classes } = this.props;

    return (
      <React.Fragment>
        <List>
          {notes.map((note, index) =>
            note !== "" ? (
              <React.Fragment>
                <ListItem className="pl-0">
                  <i class={`fa fa-${iconsMap.get(note.intelType)}`} aria-hidden="true" />
                  <ListItemText
                    secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
                  />
                </ListItem>
                <p>{note.note}</p>
                <Divider />
              </React.Fragment>
            ) : null
          )}
        </List>
      </React.Fragment>
    );
  }
}
相关问题