文章

实施代码

实施代码

实施代码

1
2
3
4
5
import Confirm from './Confirm';
import DateFilter from './DateFilter';

//
export {Confirm, DateFilter};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import React from 'react';
import {Dimensions, TouchableOpacity, View} from 'react-native';
import RootSiblingsManager from 'react-native-root-siblings';

const {width, height} = Dimensions.get('window');

/**
 * 弹窗管理类
 * - 支持同时弹出多个弹窗 (Modal、rn-global-modal 不支持)
 * - 不会遮挡Toast(Modal、rn-global-modal 会遮挡Toast)
 */
class ModalManger extends React.Component {
  static modalNodes = {}; // { key1: { rootNode: <A/>, onClose: () => {} }, key2: { rootNode: <B/>, onClose: () => {} }

  /**
   * 展示弹窗
   * @param options
   * @param modalView                      弹窗内所要展示的内容组件
   * @param {*} options.key                **必传** 弹窗唯一标识
   * @param {*} options.maskStyle          蒙层样式 默认值:{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }
   * @param {*} options.maskTouchClosable  弹窗蒙层是否可点击关闭
   * @param {*} options.closedCallback     弹窗关闭的回调
   * @param {*} options.animationType      弹窗动画类型: none | fade | slide-up
   */
  static show(modalView, options) {
    const {key, maskTouchClosable, closedCallback, maskStyle} = options;

    let rootNode;
    const onClose = () => {
      rootNode?.destroy();
      rootNode = null;
      closedCallback?.();
    };

    rootNode = new RootSiblingsManager(
      (
        <View
      style={[
      {
        position: 'absolute',
        width: width,
        height: height,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0,0,0,0.5)',
      },
      maskStyle,
      ]}
      >
      <TouchableOpacity

    style={{
      position: 'absolute',
      width: width,
      height: height,
    }}

  activeOpacity={1}
  onPress={(e) => {
    maskTouchClosable && this.hide(key);
  }}
  />
  {modalView}
  </View>
  )
  );
  this.modalNodes[key] = {rootNode, onClose};

  console.log('this.modalNodes:::', key);
}

static hide(key) {
  console.log(
    'this.modalNodes?.[key]?.onClose::',
    key
  );
  this.modalNodes?.[key]?.onClose?.();
  delete this.modalNodes[key];
}
}

export default ModalManger;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import React from 'react';

import ModalManger from './ModalManger';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
import {scaleSizeW} from '../../src/Utils/AdapterUtil';
import MyIcon from '../MyIcon/MyIcon';
import * as Animatable from 'react-native-animatable';

export default class Confirm extends React.Component {

  static show(msg = '', {
    cancelText = '取消',
    confirmText = '确定',
    maskTouchClosable = false,
    cancelCallback,
    confirmCallback
  }) {
    // 随机数
    const randomNum = Math.floor(Math.random() * (100000 - 1) + 1);
    const moduleKey = ConfirmModuleView.name + randomNum;

    let callback = confirmCallback;
    const onCancel = () => {
      callback = cancelCallback;
      Confirm.hide(moduleKey);
    };

    const onConfirm = () => {
      callback = confirmCallback;
      Confirm.hide(moduleKey);
    };

    ModalManger.show(
      <ConfirmModuleView
        msg={msg}
        cancelText={cancelText}
        confirmText={confirmText}
        cancelCallback={onCancel}
        confirmCallback={onConfirm}
      />, {
        key: moduleKey,
        maskTouchClosable: maskTouchClosable,
        closedCallback: () => {
          callback && callback();
        },
      });
  }

  static hide(moduleKey) {
    ModalManger.hide(moduleKey);
  }
}

const ConfirmModuleView = ({msg, cancelText = '取消', confirmText = '确定', cancelCallback, confirmCallback}) => {
  return (
    <Animatable.View
      useNativeDriver={true}
      animation="zoomIn"
      duration={300}
    >
      <View style={styles.container}>
        <View style={styles.content}>
          <MyIcon name="icon_warning" size={20} color="#F48832"/>
          <Text style={styles.text}>{msg}</Text>
        </View>
        <View style={styles.btnBox}>
          <TouchableOpacity
            style={styles.btnView}
            onPress={cancelCallback}
          >
            <Text style={styles.cancelText}>{cancelText}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.btnView, styles.confirmView]}
            onPress={confirmCallback}
          >
            <Text style={styles.confirmText}>{confirmText}</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Animatable.View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '80%',
    backgroundColor: '#fff',
    borderRadius: scaleSizeW(16),
  },
  content: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: scaleSizeW(40),
    paddingRight: scaleSizeW(60),
    paddingTop: scaleSizeW(40),
    paddingVertical: scaleSizeW(20),
  },
  text: {
    color: '#333333',
    fontSize: scaleSizeW(28),
    marginLeft: scaleSizeW(20),
    lineHeight: scaleSizeW(48),
  },
  btnBox: {
    height: scaleSizeW(92),
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderTopWidth: scaleSizeW(1),
    borderTopColor: '#F2F3F5'
  },
  btnView: {
    width: '50%',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  confirmView: {
    borderLeftWidth: scaleSizeW(1),
    borderLeftColor: '#F2F3F5'
  },
  cancelText: {
    color: '#2C87FC',
    fontSize: scaleSizeW(24),
  },
  confirmText: {
    color: '#1D212A',
    fontSize: scaleSizeW(24),
  }
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
 * 日期筛选组件
 * 模式一:使用默认结构 icon
 * 模式二:使用自定义结构 view
 * 模式三:调用静态方法 show
 * */

import React, {useEffect, useState, Component} from 'react';
import ModalManger from './ModalManger';
import {TouchableOpacity, View, StyleSheet, Text, Dimensions} from 'react-native';
import MyIcon from '../MyIcon/MyIcon';
import * as Animatable from 'react-native-animatable';
import {isEmpty, scaleSizeW} from '../../src/Utils/AdapterUtil';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import moment from 'moment';
import Toast from 'react-native-root-toast';

const {width} = Dimensions.get('window');

class DateFilter extends Component {
  constructor(props) {
    super(props);
  }

  static show(options) {
    this.onPress(options);
  }

  static onPress = (options) => {
    const {
      cancelText = '清空',
      confirmText = '确定',
      cancelCallback,
      confirmCallback,
      maskTouchClosable = true,
      initialDate,
    } = options;

    // 随机数
    const randomNum = Math.floor(Math.random() * (100000 - 1) + 1);
    const moduleKey = ModalManger.name + randomNum;

    let callback = null;
    const onCancel = (date) => {
      callback = cancelCallback && cancelCallback(date);
      ModalManger.hide(moduleKey);
    };

    const onConfirm = (date) => {
      const {start_date, end_date} = date;
      if ((start_date && end_date) || (!start_date && !end_date)) {
        callback = confirmCallback && confirmCallback(date);
        ModalManger.hide(moduleKey);
      } else {
        return Toast.show('请选择开始日期或结束日期');
      }
    };

    ModalManger.show(
      <ModalView
        initialDate={initialDate}
        cancelText={cancelText}
        confirmText={confirmText}
        cancelCallback={onCancel}
        confirmCallback={onConfirm}
      />, {
        key: moduleKey,
        maskTouchClosable: maskTouchClosable,
        maskStyle: {justifyContent: 'flex-end'},
        closedCallback: (e) => {
          callback && callback(e);
        },
      });
  };

  render() {
    const {view} = this.props;
    return (
      <TouchableOpacity onPress={() => DateFilter.onPress(this.props)}>
        {
          view ? (
            view
          ) : (
            <MyIcon name={'filtrate'} size={20} color="#1E1E1E"/>
          )
        }
      </TouchableOpacity>
    );
  }
}

export default DateFilter;

const ModalView = (props) => {
  const {cancelText, confirmText, cancelCallback, confirmCallback, initialDate} = props;

  const [state, setState] = useState({
    start_date: '',
    end_date: ''
  });
  const [currentIndex, setCurrentIndex] = useState(-1);
  const [currentType, setCurrentType] = useState('start_date');
  const [timePickerVisible, setTimePickerVisible] = useState(false);
  const [initialTimeValue, setInitTimeValue] = useState(new Date());

  useEffect(() => {
    if (isEmpty(initialDate)) {
      return;
    }
    setState({...initialDate});
  }, [initialDate]);

  useEffect(() => {
    const {start_date, end_date} = state;
    if (end_date !== moment().format('YYYY-MM-DD')) {
      return;
    }
    // 今天
    if (start_date === moment().format('YYYY-MM-DD')) {
      setCurrentIndex(0);
    }
    // 本周
    if (start_date === moment().subtract(7, 'days').format('YYYY-MM-DD')) {
      setCurrentIndex(1);
    }
    // 本月
    if (start_date === moment().subtract(1, 'months').format('YYYY-MM-DD')) {
      setCurrentIndex(2);
    }
  }, [state]);

  // 显示选择日期
  const onChooseDate = (type) => {
    setCurrentType(type);
    setTimePickerVisible(true);
    let initDate = new Date();
    if (type === 'start_date') {
      initDate = state.start_date ? new Date(moment(state.start_date).year(), moment(state.start_date).month(), moment(state.start_date).date()) : new Date();
    } else {
      initDate = state.end_date ? new Date(moment(state.end_date).year(), moment(state.end_date).month(), moment(state.end_date).date()) : new Date();
    }
    setInitTimeValue(initDate);
  };

  // 选择日期
  const handleDate = (date) => {
    setTimePickerVisible(false);
    const newState = {...state, [currentType]: moment(date).format('YYYY-MM-DD')};
    if (currentType === 'start_date') {
      newState.end_date = '';
    }
    setState({...newState});
  };

  const {start_date, end_date} = state;
  const minimumDate = start_date && currentType === 'end_date' ? new Date(moment(state.start_date).year(), moment(state.start_date).month(), moment(state.start_date).date()) : null;
  return (
    <Animatable.View
      useNativeDriver={true}
      animation="slideInUp"
      duration={300}
    >
      <View style={styles.container}>
        <View style={styles.btnBox}>
          <TouchableOpacity
            style={styles.btnView}
            onPress={() => {
              const emptyDate = {start_date: '', end_date: ''};
              setState(emptyDate);
              cancelCallback(emptyDate);
            }}
          >
            <Text style={styles.cancelText}>{cancelText}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.btnView}
            onPress={() => confirmCallback(state)}
          >
            <Text style={styles.confirmText}>{confirmText}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.shortcutBox}>
          <TouchableOpacity
            activeOpacity={0.8}
            style={[styles.shortcutView, currentIndex === 0 && styles.active]}
            onPress={() => {
              setState({
                start_date: moment().format('YYYY-MM-DD'),
                end_date: moment().format('YYYY-MM-DD'),
              });
            }}
          >
            <Text style={[styles.shortcutText, currentIndex === 0 && styles.activeText]}>今天</Text>
          </TouchableOpacity>
          <TouchableOpacity
            activeOpacity={0.8}
            style={[styles.shortcutView, currentIndex === 1 && styles.active]}
            onPress={() => {
              setState({
                start_date: moment().subtract(7, 'days').format('YYYY-MM-DD'),
                end_date: moment().startOf('days').format('YYYY-MM-DD'),
              });
            }}
          >
            <Text style={[styles.shortcutText, currentIndex === 1 && styles.activeText]}>本周</Text>
          </TouchableOpacity>
          <TouchableOpacity
            activeOpacity={0.8}
            style={[styles.shortcutView, currentIndex === 2 && styles.active]}
            onPress={() => {
              setState({
                start_date: moment().subtract(1, 'months').format('YYYY-MM-DD'),
                end_date: moment().startOf('days').format('YYYY-MM-DD'),
              });
            }}
          >
            <Text style={[styles.shortcutText, currentIndex === 2 && styles.activeText]}>本月</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.dateBox}>
          <TouchableOpacity style={styles.dateView} onPress={() => onChooseDate('start_date')}>
            {
              start_date ? (
                <Text style={styles.dateText2}>{start_date}</Text>
              ) : (
                <Text style={styles.dateText}>自定义开始日期</Text>
              )
            }
          </TouchableOpacity>
          <Text style={styles.dateText}></Text>
          <TouchableOpacity style={styles.dateView} onPress={() => onChooseDate('end_date')}>
            {
              end_date ? (
                <Text style={styles.dateText2}>{end_date}</Text>
              ) : (
                <Text style={styles.dateText}>自定义结束日期</Text>
              )
            }
          </TouchableOpacity>
        </View>
        <DateTimePickerModal
          mode="date"
          confirmTextIOS="确定"
          cancelTextIOS="取消"
          onConfirm={handleDate}
          date={initialTimeValue}
          minimumDate={minimumDate}
          isVisible={timePickerVisible}
          onCancel={() => setTimePickerVisible(false)}
        />
      </View>
    </Animatable.View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: width,
    backgroundColor: '#fff',
    paddingBottom: scaleSizeW(150),
    paddingHorizontal: scaleSizeW(32),
    borderTopLeftRadius: scaleSizeW(40),
    borderTopRightRadius: scaleSizeW(40),
  },
  btnBox: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingTop: scaleSizeW(45),
    paddingBottom: scaleSizeW(35),
  },
  btnView: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  cancelText: {
    color: '#878F9B',
    fontSize: scaleSizeW(28),
  },
  confirmText: {
    color: '#2E83FF',
    fontSize: scaleSizeW(28),
  },
  shortcutBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  shortcutView: {
    width: '30%',
    height: scaleSizeW(62),
    backgroundColor: '#F1F1F1',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: scaleSizeW(8),
  },
  active: {
    backgroundColor: '#0E9CFF',
  },
  activeText: {
    color: '#FFFFFF',
  },
  shortcutText: {
    color: '#1D212A',
    fontSize: scaleSizeW(28),
  },
  dateBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: scaleSizeW(30),
  },
  dateView: {
    width: '45%',
    height: scaleSizeW(62),
    backgroundColor: '#F1F1F1',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: scaleSizeW(8),
  },
  dateText: {
    color: '#878F9B',
    fontSize: scaleSizeW(28),
  },
  dateText2: {
    color: '#1D212A',
    fontSize: scaleSizeW(28),
  }
});

使用:

  • Confirm
1
2
3
4
5
6
7
8
import {Confirm} from '../component/Modals';

Confirm.show('当前项目己选定,如需切换组织,请到我的 使用“组织切换“功能。', {
  confirmText: '切换',
  confirmCallback: () => {
    this.navigation.navigate('Organization');
  },
});

1727572648015-60b564fc-928f-4ce8-8932-b15ada351fa7.png

  • DateFilter
1
2
3
4
5
6
7
8
9
10
11
12
13
import {DateFilter} from '../component/Modals';

<DateFilter

  initialDate={{start_date: this.inspect_date_start, end_date: this.inspect_date_end}}

  cancelCallback={() => {
    this.clearDate();
  }}
  confirmCallback={(date) => {
    this.handleDate(date);
  }}
/>

1727572667893-3489d4b4-493b-4e3a-b876-2ad440d7a9b6.png

本文由作者按照 CC BY 4.0 进行授权