UNPKG

1.83 kBTypeScriptView Raw
1import React, { Component } from 'react'
2import { View, Text, DeviceEventEmitter } from 'react-native'
3import math from 'mathjs'
4import kindOf from 'kind-of'
5import { CalculateProps } from '../utils/PropTypes'
6
7class SsCalculateView extends Component<any, any> {
8 render() {
9 const { title, computedValue } = this.props
10 return (
11 <View
12 style={{ paddingHorizontal: 20, paddingVertical: 8, justifyContent: 'space-between', flexDirection: 'row' }}
13 >
14 <Text>{title}</Text>
15 <Text>{computedValue}</Text>
16 </View>
17 )
18 }
19}
20
21export default class SsCalculate extends Component<CalculateProps, any> {
22 private subscription: any
23 static defaultProps = {
24 required: false,
25 textAlign: 'right',
26 upper: true,
27 }
28
29 constructor(props) {
30 super(props)
31 this.state = {
32 value: 0,
33 }
34 }
35
36 componentDidMount() {
37 this.subscription = DeviceEventEmitter.addListener('SsDynamicFormValueChanged', ({ values }) => {
38 this.refresh(values)
39 })
40 }
41
42 componentWillUnmount() {
43 this.subscription.remove()
44 }
45
46 refresh = (values: any) => {
47 try {
48 const { formula } = this.props
49 let expression = ''
50 const calElements = formula.map(item => {
51 return kindOf(item) === 'object' ? values[item.id] || '0' : item
52 })
53 calElements.forEach(item => {
54 expression += item.toString()
55 })
56 console.log(expression)
57 const value = math.eval(expression).toFixed(2, 10)
58 this.setState({
59 value: value === 'Infinity' || isNaN(value) ? '' : value,
60 })
61 } catch (error) {
62 console.log(error)
63 }
64 }
65
66 render() {
67 const { label, placeholder } = this.props
68 const { value } = this.state
69 return <SsCalculateView title={label} placeholder={placeholder} computedValue={value} />
70 }
71}