我正在尝试创建一个只接受数字但初始值为 null
的 React Native TextInput。然后,此值可以递增/递减 1。我很难将初始值转换为空值。我的想法是我必须以某种方式将 null 设置为空字符串,但不完全确定如何做到这一点。
以数值开始输入,我就有它,一切正常,但是如果我将其设置为 null,它将无法读取 null 的字符串。任何帮助将不胜感激。
export class Measurement extends Component {
state = {
measurement: null
};
updateMeasurement = measurement => {
this.setState({
measurement: +measurement
});
};
decrement = () => {
this.setState({
measurement: this.state.measurement - 1
});
};
increment = () => {
this.setState({
measurement: this.state.measurement + 1
});
};
render() {
const styles = getStyles();
return (
<View style={styles.container}>
<View style={styles.input}>
<TextInput
style={styles.inputText}
onChange={this.updateMeasurement}
keyboardType="numeric"
placeholder="Enter #"
value={this.state.measurement.toString()}
/>
</View>
<View style={styles.buttonWrapper}>
<Button
buttonStyles={styles.decrementButton}
onPress={this.decrement}
textStyles={styles.decrementButtonText}
>
__
</Button>
<Button
buttonStyles={styles.incrementButton}
onPress={this.increment}
textStyles={styles.buttonText}
>
+
</Button>
</View>
</View>
</BaseType>
);
}
}
getMeasurement() {
return this.state.measurement && this.state.measurement.toString();
}
...
<TextInput
style={styles.inputText}
onChange={this.updateMeasurement}
keyboardType='numeric'
placeholder='Enter #'
value={this.getMeasurement()}
/>