您好我有一个sectionList,它传递了一系列颜色+背景图像,这些图像随机选择呈现为每个行项目的背景。当我滑动访问该视图时,由于随机选择仍在进行,颜色会闪烁几秒钟。每次我带着列表返回屏幕时,颜色会闪烁几秒钟然后稳定下来。如何在没有闪烁的情况下,在加载时随机选择颜色?
class Main extends React.Component {
constructor(props, context) {
super(props, context);
// app state
this.state = {
listColor: [
['rgba(0,36,155,0.8)', 'rgba(26,0,87,0.8)'],
['rgba(155,0,0,0.8)', 'rgba(87,0,0,0.8)']],
}
}
_handleRandomIndex(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
_renderItem = ({item, section}) => (
<TouchableScale
style={styles.row}
onPress={this._onRowPress.bind(this, item)}
activeScale={0.94}
tension={0}
friction={3}
>
<View style={ styles.elevationLow } borderRadius={9} >
<ImageBackground source={{uri: this._handleRandomIndex(item.bgImgs).image_link }} borderRadius={9} style={ styles.imageBackground }>
<LinearGradient
colors={ this._handleRandomIndex(this.state.listColor) }
start={[0.1,0.1]}
end={[0.5,0.5]}
style={{ padding: 20, borderRadius: 9 }}>
</LinearGradient>
</ImageBackground>
</View>
}
</TouchableScale>
)
}
答案 0 :(得分:1)
因为您每次重新渲染都在进行Math.random。因此,只要render函数调用,它就会改变颜色。
更改为:
function _handleRandomIndex(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
class Main extends React.Component {
state = {
listColor: [
['rgba(0,36,155,0.8)', 'rgba(26,0,87,0.8)'],
['rgba(155,0,0,0.8)', 'rgba(87,0,0,0.8)']
]
}
_renderItem = ({ item, section }) => <Item item={item} listColor={this.state.listColor} />
}
class Item extends Component {
rando = _handleRandomIndex(this.props.listColor);
render() {
const { item } = this.props;
return (
<TouchableScale
style={styles.row}
onPress={this._onRowPress.bind(this, item)}
activeScale={0.94}
tension={0}
friction={3}
>
<View style={styles.elevationLow} borderRadius={9}>
<ImageBackground source={{ uri: this._handleRandomIndex(item.bgImgs).image_link }} borderRadius={9} style={styles.imageBackground}>
<LinearGradient
colors={this.rando}
start={[0.1, 0.1]}
end={[0.5, 0.5]}
style={{ padding: 20, borderRadius: 9 }}>
</LinearGradient>
</ImageBackground>
</View>
</TouchableScale>
)
}
}
答案 1 :(得分:0)
Noitidart的答案会有效但所有项目都会被随机化为相同的颜色,如果您希望每件商品都有不同的颜色,我认为您需要这样做:
_renderItem = ({item, section}) => {
const color = this._handleRandomIndex(this.state.listColor);
return (
<TouchableScale
style={styles.row}
onPress={this._onRowPress.bind(this, item)}
activeScale={0.94}
tension={0}
friction={3}
>
<View style={ styles.elevationLow } borderRadius={9} >
<ImageBackground source={{uri: this._handleRandomIndex(item.bgImgs).image_link }} borderRadius={9} style={ styles.imageBackground }>
<LinearGradient
colors={ color }
start={[0.1,0.1]}
end={[0.5,0.5]}
style={{ padding: 20, borderRadius: 9 }}>
</LinearGradient>
</ImageBackground>
</View>
}
</TouchableScale>
)
}