我可以向ListView单元格中添加静态图像(请参见下面的代码),但是如何动态更改图标图像?
ListView
从React Native Docs
<Image source={require('./img/check.png')} />
是推荐用于iOS和Android的图像文件引用的方法。
我有一个名为的组件ExpandingCell,可以选择显示一堆不同的图标,但其他所有元素都保持不变。
ExpandingCell
在中,ListView我创建一个cell对象,然后将其传递到中ExpandingCell进行渲染
cell
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.'}, ... ];
然后在renderCell方法中将其传递给上述单元格对象:
renderCell
renderCell(cell) { if (cell.type === 'ExpandingCell') { return ( <ExpandingCell cell={cell} /> ); } }
现在,ExpandingCell我有这个目的render():
render()
render() { return ( ... <Image source{ require('./CellIcons/MagnifyingGlassIcon.png') }> </Image> ... ); }
但是,当我尝试使用this.props.cell.icon这样的方法时:
this.props.cell.icon
<Image source={require(this.props.cell.icon)}></Image>
我收到以下错误: Requiring unknown module "./CellIcons/MagnifyingGlassIcon.png".
Requiring unknown module "./CellIcons/MagnifyingGlassIcon.png".
在此先感谢=)
包装期间必须知道图像。docs中有关于它的一节。
将其放在定义ExpandingCell的文件的顶部:
const MAGNIFYING_GLASS_ICON = require('./CellIcons/MagnifyingGlassIcon.png');
然后你可以像这样使用常量
let icon = someCondition ? MAGNIFYING_GLASS_ICON : SOME_OTHER_ICON; <Image source={icon}/>
您必须在那里拥有要使用此方式的所有图像的需求。