本著我為人人,人人為我的精神,敲過的代碼就要分享出來!
項目需要做一個文字的輪播,開始想著是由下而上的滾動,但是還是寫的不是很好,就先退而求其次,通過透明度來實現文字的滾動了(也不能說是滾動了,是切換)。
為了貼上來還是寫了些注釋的,也就不一一的解釋了,很簡單的代碼,看注釋就好了。(我就是懶)
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要用的話改一下標簽就好了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答