【发布时间】:2017-06-27 05:54:12
【问题描述】:
我试图通过简单地每 500 毫秒切换一次图像来为 React Native 中的图标设置动画。我的代码如下所示:
export default class FlashingIcon extends Component {
constructor(props) {
super(props);
this.state = {
on: true,
};
setInterval(() => {
this.setState(previousState => {
return {
on: !previousState.on,
};
});
}, 500);
}
render() {
let sprite = this.state.on
? require('../onIcon.png')
: require('../offIcon.png');
return (
<Image
source={sprite}
style={{width:16, height:20}}
/>
);
}
}
代码基本上是从以下位置复制粘贴的:
- https://facebook.github.io/react-native/docs/state.html 和
- https://facebook.github.io/react-native/docs/images.html
如果我将require 复制到<Image> 中,每个图像都会显示。我还可以验证,如果我改为渲染输出 this.state.on 的 <Text> 元素,它会交替显示正确的值。
我终其一生都无法弄清楚我做错了什么。
【问题讨论】:
-
@JigarShah 我不确定您要指出什么?为简洁起见,我省略了导入,但它们在那里(图像确实呈现,只是不会在提供的两个图像之间切换)
-
而不是将其分配给
let,您可以直接在source上添加条件 -
@JigarShah 也不起作用。
-
它对我有用。但是,直到我把它放大很多,图像才显示出来。
-
image的密钥如下:<Image key={this.state.on}。一旦状态改变,它将有助于重新渲染图像。
标签: react-native