温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在react中使用native实现文字轮播

发布时间:2021-06-02 17:01:01 来源:亿速云 阅读:323 作者:Leah 栏目:web开发

怎么在react中使用native实现文字轮播?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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} />

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI