Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class Converter extends React.Component {
- constructor(props)
- {
- super(props);
- const units = [];
- const leftValue = 0;
- const rightValue = 0;
- const rounding = 5;
- const leftUnit = "kN";
- const rightUnit = "kN";
- const combinable = true;
- this.state = { leftValue, rightValue, rounding, leftUnit, rightUnit, units, combinable }
- }
- render() {
- let me = this;
- function isValidNumber(s)
- {
- return !!/^\d+(\.\d*)?$/.exec(s);
- }
- function isValidInteger(s)
- {
- return ((!!/^\d+$/.exec(s) && s <= 12) || s == "");
- }
- console.log(`render(): this.state.rounding = ${this.state.rounding}`);
- const canConvert = (isValidNumber(this.state.leftValue) && isValidInteger(this.state.rounding));
- return (
- <View>
- <View>
- <View style={[styles.inline, styles.center]}>
- <TextInput style={[{width: 100}, styles.margins]} value={"" + this.state.leftValue} onChangeText={(s) => this.setState({leftValue: s})} keyboardType='numeric'/>
- <Text>{this.state.leftUnit}</Text>
- </View>
- <View style={[styles.inline, styles.center]}>
- <TextInput style={[{width: 100}, styles.margins]} value={"" + this.state.rounding} onChangeText={(s) => this.setState({rounding: s})} keyboardType='numeric'/>
- <Text>Decimals (0-12)</Text>
- </View>
- <Picker selectedValue={this.state.leftUnit} onValueChange={(itemValue, itemIndex) => { this.setState({leftUnit: itemValue})} }>
- {Object.keys(this.state.units).map((key) => {
- return (<Picker.Item key={key} label={key} value={key}/>)
- })}
- </Picker>
- <Picker style={styles.margins} selectedValue={this.state.rightUnit} onValueChange={(itemValue, itemIndex) => this.setState({rightUnit: itemValue})}>
- {Object.keys(this.state.units).map((key) => {
- return (<Picker.Item key={key} label={key} value={key}/>)
- })}
- </Picker>
- <View style={styles.center}>
- <Text style={styles.margins} >{this.state.rightValue} {this.state.rightUnit}</Text>
- </View>
- <Button title="Convert" onPress={() => this.convert()} disabled={!canConvert} />
- </View>
- </View>
- );
- }
- convert() {
- const { factor: fromValFactor } = this.state.units[this.state.leftUnit];
- const { factor: toValFactor } = this.state.units[this.state.rightUnit];
- const endValue = this.state.leftValue * fromValFactor / toValFactor;
- if (this.state.rounding == null) {
- this.setState({rightValue: ((this.state.leftValue * fromValFactor) / toValFactor)});
- } else {
- this.setState({rightValue: ((this.state.leftValue * fromValFactor) / toValFactor).toFixed(this.state.rounding)});
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement