The following example scenario is written by myself after I read the official document.
Please refer to: Official document: Status Improvement
The following scenarios are the same as the temperature conversion scenarios in the official documents: Temperature value conversion scenario
Let's start my scene,
Example:
First of all, you need to know that an A item is 200 yuan.
There are two input fields, corresponding to price and quantity.
Function display:
(1) When you enter a number (e.g. 201) in the first input box, the second input box will automatically display how many items you can buy. Here is one
(2) Similarly, when you type in the second input box (for example: 3), the first input box will automatically display how much you need (here: 600) to buy three items.
(3) Of course, when you don't type a number in any input box, nothing happens in the other.
Source code:
function inputProtected(input){
if(Number.isNaN(input) || input <= 0){
return '';
}else{
return Math.floor(input).toString();
}
}
let dataTitle = {
m:'How much does it cost:',
n:'Can buy so many:'
};
class Calculation extends React.Component{
render(){
let data = this.props.data;
let title = this.props.title;
let changeDate = this.props.changeDate;
return (
<div>
<fieldset>
<legend>{title}</legend>
<input type="text" value={data}onChange={changeDate}/>
</fieldset>
</div>
);
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {type:'money',input:''};
}
handleDate(type,e){
if(type === 'money'){
this.setState({type:'money',input:e.target.value});
}else if(type === 'number'){
this.setState({type:'number',input:e.target.value});
}
}
convertNumber(input){
return Math.floor(input/200);
}
convertMoney(input){
return input * 200;
}
render(){
let input = this.state.input;
let type = this.state.type;
let number = type==='money' ? inputProtected(this.convertNumber.bind(this,input)()) : input;
let money = type==='number' ? inputProtected(this.convertMoney.bind(this,input)()) : input;
return (
<div>
<h4>Price:200Yuan a</h4>
<Calculation
data={money}
title={dataTitle.m}
changeDate={(e)=>this.handleDate('money',e)}
/>
<Calculation
data={number}
title={dataTitle.n}
changeDate={(e)=>this.handleDate('number',e)}
/>
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById('root'));