react-native版文字跑马灯

Posted xpin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react-native版文字跑马灯相关的知识,希望对你有一定的参考价值。

js部分

interface IProps {
  text: string,
  style?: object,
}
interface IState {
  transformX: any,
  viewWidth: number,
  textWidth: number,
}

const FlexItem = Flex.Item;
const Speed = 10000
export default class Notice extends React.PureComponent<IProps, IState> {
  state: IState = {
    transformX: new Animated.Value(0),
    viewWidth: 0,
    textWidth: 0,
  }
  constructor (props: IProps) {
    super(props)
  }
  onTextLayout = (event: any) => {
    const { width } = event.nativeEvent.layout;
    this.setState({
      textWidth: width
    })
  }
  onViewLayout = (event: any) => {
    const { width } = event.nativeEvent.layout;
    this.setState({
      viewWidth: width
    })
  }
  move () {
    const { viewWidth, textWidth, transformX } = this.state;
    if (textWidth > viewWidth) {
      let duration = Speed
      duration += ((textWidth - viewWidth) / viewWidth) * Speed;
      transformX.setValue(viewWidth)
      Animated.timing(transformX, {
        toValue: -textWidth,
        duration: duration,
        easing: Easing.linear,
        useNativeDriver: false
      }).start(({finished}) => {
        if (finished) {
          this.move()
        }
      })
    }
  }
  componentDidUpdate () {
    this.move()
  }
  renderContent(text: string) {
    const { transformX, textWidth } = this.state;
    return <Animated.View style={[styles.animatedView, { width: textWidth, transform: [{ translateX: transformX }] }]}>
      <Text numberOfLines={1}>
        {text}
      </Text>
    </Animated.View>
  }
  render() {
    const { text, style = {} } = this.props;
    return <View onLayout={this.onViewLayout} style={[styles.view, style]}>
      <Flex direction="row">
        <FlexItem style={{ flexDirection: \'row\' }}>
          {this.renderContent(text)}
        </FlexItem>
      </Flex>
      <View style={styles.hide}>
        <Text onLayout={this.onTextLayout} numberOfLines={1} style={[styles.hide]}>
          {text}
        </Text>
      </View>
    </View>
  }
}

css部分

const styles = StyleSheet.create({
  view: {
    paddingVertical: 24,
    overflow: \'hidden\'
  },
  normalView: {
    paddingLeft: 24,
  },
  animatedView: {
    flexDirection: \'row\',
  },
  hide: {
    flexDirection: \'row\',
    opacity: 0,
    zIndex: -1,
    position: \'absolute\',
    top: 0,
  },
});

以上是关于react-native版文字跑马灯的主要内容,如果未能解决你的问题,请参考以下文章

ShimmerTextView

文字的跑马灯特效

jQuery+CSS3文字跑马灯特效

VUE之文字跑马灯效果

微信小程序-实现文字跑马灯-wepy

代码笔记文字走马灯效果