先上图:
Barrage.js
import React, {Component} from 'react';
import {
Text,
View,
Easing,
Animated,
Dimensions
} from 'react-native';
const {width} = Dimensions.get('window')
const getRandomColor = () => {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
const getRandomNum = (Min, Max) => {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
class BarrageView extends Component {
constructor(props) {
super(props)
this.state = {
left: new Animated.Value(0)
}
}
componentDidMount() {
this.begin();
}
render() {
let {text} = this.props;
return <Animated.View
removeClippedSubviews={true}
style={{
top: getRandomNum(0, 10),
left: this.state.left.interpolate({
inputRange: [0, 1],
outputRange: [width, -width]
})
}}>
<Text style={[{
fontSize: getRandomNum(12, 40),
color: getRandomColor(),
backgroundColor: '#00000000'
}, styles.text]}>{text}</Text>
</Animated.View>
}
begin() {
Animated.timing(this.state.left, {
toValue: 1,
duration: 2 * getRandomNum(5000, 9000),
easing: Easing.linear
}).start();
}
}
export default class Barrage extends Component {
render() {
let views = this.props.list.map((text, index) => {
return <BarrageView key={index} text={text}/>
})
return <View
pointerEvents='none'
removeClippedSubviews={true}
style={{
backgroundColor: '#00000000',
justifyContent: 'space-around',
overflow: 'hidden',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
}}>
{views}
</View>
}
}
const styles = {
text: {
// borderWidth:StyleSheet.hairlineWidth,
// borderColor:getRandomColor(),
// backgroundColor:'red'
}
}
用法:
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
import ./Barrage.js
const list = ['喜腾官方旗舰店', '百万庄大街粮科大厦', '傻逼', '默认情况下', '王强', '13', '刘殿琪', '猪猪侠', '🐷', '么么哒', '琳琳', '振国', , '王强', '13', '刘殿琪', '猪猪侠', '🐷', '么么哒', '琳琳', '振国',];
class HelloWorldApp extends Component {
render() {
return (
<Text>Hello world!</Text>
<Barrage list={list}/>
);
}
}
// 注意,这里用引号括起来的'HelloWorldApp'必须和你init创建的项目名一致
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);