'How react binds events to elements generated by map
When I click discountKeyboard
,it reported a mistake:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
Here is the code:
<View style={[styles.modalStyle, { display: this.state.DiscountVisible ? 'flex' : 'none', position: this.state.DiscountVisible ? 'absolute' : 'relative' }]} >
<TouchableOpacity style={{ alignItems: 'flex-end' }} onPress={() => this.setState({ DiscountVisible: false })} >
<AntDesign name="close" size={width <= 900 ? 18 : 23} color="black" />
</TouchableOpacity>
<Text style={{ fontFamily: 'Regular', fontSize: width <= 1024 ? 18 : 22, marginBottom: 10 }} >{translate ? '输入折扣金额' : 'Enter Discount Amount'}</Text>
<Text style={{ fontFamily: 'Regular', fontSize: width <= 1024 ? 18 : 22, marginBottom: 10 }} >{translate ? '税率' : 'Tax Rate'}: 8.00%</Text>
<View>
<Text style={[styles.testInputStyle]} >{this.state.discount}</Text>
<View style={{ flexDirection: 'row' }} >
<View style={{ width: width <= 1024 ? 194 : 230, flexDirection: 'row', flexWrap: 'wrap' }} >
{
this.number.map((item, index) => {
return (
<TouchableOpacity key={index} style={styles.numberStyle} onPress={() => this.discountKeyboard(item)} >
<Text style={{ fontFamily: 'Regular', }}>{item}</Text>
</TouchableOpacity>
)
})
}
</View>
<View>
<TouchableOpacity style={[styles.numberStyle, { height: width <= 1024 ? 121 : 150 }]} onPress={() => this.discountKeyboard('delete')} >
<Feather name="delete" size={20} color="black" />
</TouchableOpacity>
<TouchableOpacity style={[styles.numberStyle, { height: width <= 1024 ? 121 : 150 }]} onPress={() => this.discountKeyboard('ok')} >
<AntDesign name="check" size={20} color="black" />
</TouchableOpacity>
</View>
</View>
</View>
</View>
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '.', '%']
discountKeyboard = (keyboard) => {
if (keyboard === 'delete') {
var p = this.state.discount
var data = p.substr(0, p.length - 1)
this.setState({ discount: data })
} else if (keyboard === 'ok') {
var op = this.state.discount
var p = this.state.finalDiscount
this.setState({
DiscountVisible: false,
finalDiscount: parseFloat(this.state.discount),
total: this.state.total + parseFloat(p) - parseFloat(op)
})
} else {
this.setState({
discount: preState => preState + keyboard
})
}
}
Solution 1:[1]
I already know the problem
this.setState({
discount: preState => preState + keyboard
})
discount: preState => preState + keyboard
is the wrong way to write it,and discount: this.state.discount+ keyboard
is right.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | water12 |