tsx:
import React, { Component } from 'react' import Taro from '@tarojs/taro' import { View, Text, ScrollView } from '@tarojs/components' import classnames from 'classnames' import NavBar from '@components/navbar' import './index.scss' const observer: any = null class Test extends Component { constructor(props) { super(props) this.state = { appear: false } } componentDidMount() { Taro.createIntersectionObserver(this, { thresholds: [0, 0.25, 0.5, 0.75], observeAll: true }) .relativeTo('.scroll-view') .observe('.ball', (res) => { console.log(res, "test"); this.setState({ appear: res.intersectionRatio > 0 }) }) } // 对应 onShow componentDidShow() { } // 对应 onHide componentDidHide() { if (observer) { observer.disconnect() } } // 对应 onError componentDidCatchError() { } render() { const { appear }: any = this.state return ( <View className="container"> <NavBar title="监听小球" /> <View className="page-body"> <View className="page-section message"> <Text> {appear ? '小球出现' : '小球消失'} </Text> </View> <View className="page-section"> <ScrollView className={classnames('scroll-view')} scrollY> <View className="scroll-area"> <Text className="notice">向下滚动让小球出现</Text> <View className="filling"></View> <View className={classnames('ball')}></View> </View> </ScrollView> </View> </View> </View> ) } } export default Test
scss:
.scroll-view { height: 400px; background: #fff; border: 1px solid #ccc; box-sizing: border-box; } .scroll-area { height: 2600px; display: flex; flex-direction: column; align-items: center; transition: 0.5s; } .notice { margin-top: 300px; } .ball { width: 400px; height: 400px; background: #1aad19; border-radius: 50%; } .filling { height: 800px; } .message { width: 100%; display: flex; justify-content: center; } .message text { font-size: 80px; font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif; }