react native 文字轮播的实现示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

react native 文字轮播的实现示例

chaecho   2020-05-16 我要评论

本着我为人人,人人为我的精神,敲过的代码就要分享出来!

项目需要做一个文字的轮播,开始想着是由下而上的滚动,但是还是写的不是很好,就先退而求其次,通过透明度来实现文字的滚动了(也不能说是滚动了,是切换)。

为了贴上来还是写了些注释的,也就不一一的解释了,很简单的代码,看注释就好了。(我就是懒)

import React, { Component } from "react"
import { View, Text, TouchableOpacity } from "react-native"

export default class TextLantern extends Component {
  constructor(props) {
    super(props)
    this.state = {
      nowText: "", // 显示的文本
      opacity: 1, // 透明度
      index: 0, // 下标
      list: [], // 滚动的列表
    }
  }

  componentWillMount() {
    const { list } = this.props
    this.setState({
      nowText: list[0].title, // 插入显示的文本
      list, // 滚动的列表
    })
    this.onStart() // 启动计时器 A
  }

  onStart = () => {
    const { Intervals = 5000 } = this.props // Intervals 可为参数非必传
    this.timer = setInterval(() => {
      this.onDisappear() // 间隔Intervals毫秒启动计时器B
    }, Intervals)
  };

  onDisappear = () => {
    this.timer1 = setInterval(() => {
      const { opacity, index, list } = this.state
      if (opacity === 0) {
        // 当透明度为0时候开始显示在一个文本
        if (index + 2 > list.length) {
          // 当前显示的文本为最后一个时 重头再来
          this.setState({
            nowText: list[0].title,
            index: 0,
          })
        } else {
          this.setState({
            nowText: list[index + 1].title, // 下一个文本
            index: index + 1,
          })
        }
        this.onAppear() // 显示
        clearInterval(this.timer1)
        return
      }
      this.setState({
        opacity: parseFloat(Math.abs(opacity - 0.04).toFixed(2)),
      })
    }, 20)
  };

  onAppear = () => {
    this.timer2 = setInterval(() => {
      const { opacity } = this.state
      if (opacity === 1) {
        clearInterval(this.timer2)
        return
      }
      this.setState({
        opacity: parseFloat(Math.abs(opacity + 0.04).toFixed(2)),
      })
    }, 20)
  };

  render() {
    const { nowText, opacity, list, index } = this.state
    return (
      <View style={{ borderWidth: 1, margin: 10, padding: 5, borderColor: "#dddddd" }}>
        <TouchableOpacity activeOpacity={0.75} onPress={() => {console.log(list[index].address)}}>
          <View style={{ width: "80%" }}>
            <Text
              style={{
                opacity,
                fontSize: 14,
              }}
            >
              {nowText}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }
}

引用:

const tProps = {
      list: [
        { id: 1, title: "不是这件事很难,而是每件事都难", address: 1 },
        { id: 2, title: "稳食姐,犯法啊", address: 2 },
        { id: 3, title: "夜半诉心声,何须太高清", address: 3 },
        { id: 4, title: "失恋唱情歌,即是漏煤气关窗", address: 4 },
      ],
    }

...

<TextLantern {...tProps} />

点击跳转说一下我的做法:

通过当前的 index 来拿出对应的address进行跳转。

react要用的话改一下标签就好了。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们