• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

react-native版文字跑马灯

互联网 diligentman 2天前 4次浏览

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版文字跑马灯
喜欢 (0)