React Native numeric TextInput w /初始值为null
React Native numeric TextInput w/ initial value of null
我正在尝试创建一个只接受数字但初始值为 null
的 React Native TextInput。然后这个值可以 incremented/decremented 乘以 1。我很难将初始值转换为 null。我的想法是我必须以某种方式将 null 设置为空字符串,但不完全确定该怎么做。
目前我有它,如果我以数值开始输入,一切正常,但如果我以空值开始,它无法读取 null 的 toString。任何帮助将不胜感激。
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()}
/>
我正在尝试创建一个只接受数字但初始值为 null
的 React Native TextInput。然后这个值可以 incremented/decremented 乘以 1。我很难将初始值转换为 null。我的想法是我必须以某种方式将 null 设置为空字符串,但不完全确定该怎么做。
目前我有它,如果我以数值开始输入,一切正常,但如果我以空值开始,它无法读取 null 的 toString。任何帮助将不胜感激。
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()}
/>