如何在React Native Component中有条件地包含图像? [英] How can I conditionally include images in React Native Component?

查看:156
本文介绍了如何在React Native Component中有条件地包含图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将静态图像添加到 ListView 单元格中(请参阅下面的代码),但如何动态更改图标图像?

I am able to add static images to a ListView cell just fine (see code below), but how do I change the icon image dynamically?

来自 React Native Docs

<Image source={require('./img/check.png')} />

是推荐用于iOS和Android图像文件的方式。

is the recommended way to reference image files for both iOS and Android.

我有一个名为 ExpandingCell 的组件,它可以显示一堆不同的图标,但其他一切都保持不变。

I have a component called ExpandingCell that has the option to show a bunch of different icons but everything else remains the same.

ListView 中,我创建一个单元格对象,然后将其传递给 ExpandingCell 渲染

In a ListView I create a cell object and then pass it into the ExpandingCell to render

ListView数据源数组如下所示:

the ListView data source array looks like this:

var LIST_DATA = [
 ...
  {type: 'ExpandingCell', 
   icon: './CellIcons/MagnifyingGlassIcon.png', //unused
   title: 'Lorem Ipsum', 
   detail: 'Donec id elit non mi porta gravida at eget metus.'},
...
];

然后在 renderCell 方法中传递上面的单元格对象:

then in renderCell method it gets passed the above cell object:

renderCell(cell) {
    if (cell.type === 'ExpandingCell') {
        return (
          <ExpandingCell cell={cell} />
        );
    }
}

现在 ExpandingCell 我有这个 render()

render() {
    return (
        ...
        <Image source{
            require('./CellIcons/MagnifyingGlassIcon.png')
        }>
        </Image>
        ...
    );
}

然而,当我尝试使用时这个.props.cell.icon 喜欢这样:

However, when I try to make use of this.props.cell.icon like this:

<Image source={require(this.props.cell.icon)}></Image>

我收到以下错误:需要未知模块./CellIcons/MagnifyingGlassIcon .png。

提前致谢=)

推荐答案

包装过程中必须知道图像。在 docs 中有一节介绍它。

The images have to be known during packaging. There's a section about it in the docs.

将此放在您定义的文件的顶部ExpandingCell:

Put this at the top of the file you define ExpandingCell in:

const MAGNIFYING_GLASS_ICON = require('./CellIcons/MagnifyingGlassIcon.png');

然后你可以像这样使用常数

Then you can use the constant like this

let icon = someCondition ? MAGNIFYING_GLASS_ICON : SOME_OTHER_ICON;
<Image source={icon}/>

您必须对此处使用的所有图像都有要求。

You have to have the requires for all images you want to use this way in there.

这篇关于如何在React Native Component中有条件地包含图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆