如何在React Native Component中有条件地包含图像?

Mic*_*all 1 image reactjs react-native

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

来自React Native Docs

<Image source={require('./img/check.png')} />
Run Code Online (Sandbox Code Playgroud)

是推荐用于引用iOS和Android图像文件的方法.

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

ListView我创建一个cell对象,然后将其传递ExpandingCell给渲染

ListView数据源数组如下所示:

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

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

renderCell(cell) {
    if (cell.type === 'ExpandingCell') {
        return (
          <ExpandingCell cell={cell} />
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,ExpandingCell我有这个render():

render() {
    return (
        ...
        <Image source{
            require('./CellIcons/MagnifyingGlassIcon.png')
        }>
        </Image>
        ...
    );
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用this.props.cell.icon这样的:

<Image source={require(this.props.cell.icon)}></Image>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误: Requiring unknown module "./CellIcons/MagnifyingGlassIcon.png".

在此先感谢=)

Dan*_*dow 8

在包装过程中必须知道图像.在文档中有关于它的部分.

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

const MAGNIFYING_GLASS_ICON = require('./CellIcons/MagnifyingGlassIcon.png');
Run Code Online (Sandbox Code Playgroud)

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

let icon = someCondition ? MAGNIFYING_GLASS_ICON : SOME_OTHER_ICON;
<Image source={icon}/>
Run Code Online (Sandbox Code Playgroud)

您必须对所有想要在此处使用此图像的图像有所要求.