我正在尝试创建一个只接受数字但初始值为null
的React Native TextInput。然后该值可以递增/递减1.我很难将初始值转换为null。我的想法是我必须以某种方式将null设置为空字符串,但不完全确定如何这样做。
目前我有它,如果我用数值开始输入一切正常,但如果我把它作为null启动,它就不能读取toString为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>
);
}
}
&#13;
答案 0 :(得分:2)
getMeasurement() {
return this.state.measurement && this.state.measurement.toString();
}
...
<TextInput
style={styles.inputText}
onChange={this.updateMeasurement}
keyboardType='numeric'
placeholder='Enter #'
value={this.getMeasurement()}
/>