index.jsx 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import React, { useEffect, useMemo, useRef, useState } from 'react'
  2. import Taro from '@tarojs/taro';
  3. import { ScrollView, View, Image, Text } from '@tarojs/components';
  4. import { random } from '@/utils';
  5. import deleteIcon from '@/assets/icons/landlord/delete.png';
  6. import './style.less'
  7. export default (props) => {
  8. const { className, action, del, onDelete } = props;
  9. const contextRef = useRef()
  10. const contentHeightRef = useRef(0)
  11. const [actStyle, setActStyle]= useState()
  12. const uqClass = useMemo(() => random('f'), [])
  13. const classes = [className, 'slideview-wrapper', uqClass].filter(Boolean).join(' ');
  14. const handleScrollLeft = () => {
  15. if (contextRef.current) {
  16. contextRef.current.scrollIntoView('.slideview-content')
  17. }
  18. }
  19. const handleScrollRight = () => {
  20. if (contextRef.current) {
  21. contextRef.current.scrollIntoView('.slideview-actions')
  22. }
  23. }
  24. const handleDelete = (e) => {
  25. if (onDelete) {
  26. onDelete(e)
  27. }
  28. }
  29. useEffect(() => {
  30. Taro.nextTick(() => {
  31. Taro.createSelectorQuery()
  32. .select(`.${uqClass}`)
  33. .node()
  34. .exec((res) => {
  35. contextRef.current = res[0].node;
  36. })
  37. })
  38. }, [])
  39. useEffect(() => {
  40. Taro.nextTick(() => {
  41. // 不清楚为什么, 此处获取高度一直不准确
  42. const t = setTimeout(() => {
  43. Taro.createSelectorQuery()
  44. .select(`.${uqClass}`)
  45. .boundingClientRect()
  46. .exec((res) => {
  47. if (res && res[0]) {
  48. const { height } = res[0]
  49. if (height && height !== contentHeightRef.current) {
  50. setActStyle({
  51. height: `calc(${height}px - 30px)`,
  52. })
  53. contentHeightRef.current = height
  54. }
  55. }
  56. })
  57. clearTimeout(t)
  58. }, 500)
  59. })
  60. })
  61. return (
  62. <ScrollView
  63. className={classes}
  64. upperThreshold={20}
  65. lowerThreshold={20}
  66. scrollX
  67. scrollWithAnimation
  68. enhanced
  69. onScrollToUpper={handleScrollLeft}
  70. onScrollToLower={handleScrollRight}
  71. >
  72. <View className='slideview-content'>{props.children}</View>
  73. <View className='slideview-actions' style={actStyle}>
  74. <View className='slideview-action'>
  75. {
  76. del && (
  77. <View className='slideview-action_delete' onClick={handleDelete}>
  78. <Image src={deleteIcon} />
  79. <View>删除</View>
  80. </View>
  81. )
  82. }
  83. {action}
  84. </View>
  85. </View>
  86. </ScrollView>
  87. )
  88. }