这是我的清单:
newdiscoverPlanet: [
require('../img/sunp.png'),
require('../img/twopp.png'),
require('../img/bluep.png'),
require('../img/purplep.png'),
require('../img/bluepurplep.png'),
require('../img/redp.png'),
require('../img/orangep.png')
],
我将所有这些都放入函数中,然后在此处使用Math
getRandomPlanet = () =>{
var planetItem = this.state.newdiscoverPlanet[Math.floor(Math.random()*this.state.newdiscoverPlanet.length)];
this.setState({
changePlanet: planetItem,
});
}
然后我将它们放入选项卡以从列表中获得唯一的图像:
_renderTabIndicator() {
let tabs = [{
text: `${this.state.tags.toLowerCase()}`,
iconSource: `${this.state.changePlanet}`
},{
text: `${this.state.tags2.toLowerCase()}`,
iconSource: `${this.state.changePlanet}`
},{
text: `${this.state.tags3.toLowerCase()}`,
iconSource: `${this.state.changePlanet}`
}];
return <PagerTabIndicator tabs={tabs} />;
}
但是,每次我加载页面时,都会从每个来源获得相同的图像。有没有办法使它们独特?我该如何在React Native中执行以下操作: https://stackoverflow.com/a/2380113/9318643
答案 0 :(得分:2)
问题是您要访问3次相同的值(this.state.changePlanet),并且期望得到不同的结果。 我认为您只需要使方法 return 像这样随机行星:
getRandomPlanet = () => {
return this.state.newdiscoverPlanet[Math.floor(Math.random()*this.state.newdiscoverPlanet.length)];
}
然后您可以调用3次,您将获得3张不同的图片:
_renderTabIndicator() {
let tabs = [{
text: `${this.state.tags.toLowerCase()}`,
iconSource: this.getRandomPlanet()
},{
text: `${this.state.tags2.toLowerCase()}`,
iconSource: this.getRandomPlanet()
},{
text: `${this.state.tags3.toLowerCase()}`,
iconSource: this.getRandomPlanet()
}];
return <PagerTabIndicator tabs={tabs} />;
}
编辑:如果要确保未选择两个相同的行星,则可以执行以下操作:
getRandomPlanets = (n) => {
// Shuffle array
const shuffled = this.state.newdiscoverPlanet.sort(() => 0.5 - Math.random());
// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);
return selected;
}
然后致电:
_renderTabIndicator() {
const planets = this.getRandomPlanets(3);
let tabs = [{
text: `${this.state.tags.toLowerCase()}`,
iconSource: planets[0]
},{
text: `${this.state.tags2.toLowerCase()}`,
iconSource: planets[1]
},{
text: `${this.state.tags3.toLowerCase()}`,
iconSource: planets[2]
}];
return <PagerTabIndicator tabs={tabs} />;
}