React十进制和二进制转换的实现和分析

react

模仿官方文档的摄氏度和华氏度的转换,实现十进制和二进制的互换。

【实现】

import React from 'react';

import ReactDOM from 'react-dom';

function Convert(value,setWhat){

if(value===''){return ''}

if(setWhat==='setDec'){

return parseInt(value,2);

}else{

return parseInt(value).toString(2);

}

}

class InputBox extends React.Component{

constructor(props){

super(props);

this.handleChange=this.handleChange.bind(this);

}

handleChange(e){

//数据流向:子->父。onChange事件接受父组件的回调函数,实现把event.target.value传到父组件

this.props.callBack(e.target.value);

}

render(){

return(

<div>

<p>Input: {this.props.title}</p>

<input value={this.props.selfValue} onChange={this.handleChange} />

</div>

)

}

}

class Main extends React.Component{

constructor(props){

super(props);

this.callBack_changeDec=this.callBack_changeDec.bind(this);

this.callBack_changeBin=this.callBack_changeBin.bind(this);

this.state={

wanted:'wantDec',

result:'',

}

}

callBack_changeDec(inputValue){

this.setState({result:inputValue});

this.setState({wanted:'wantBin'});

}

callBack_changeBin(inputValue){

this.setState({result:inputValue});

this.setState({wanted:'wantDec'});

}

render(){

var result_titleIsDec=this.state.wanted==='wantBin'?this.state.result:Convert(this.state.result,'setDec');

var result_titleIsBin=this.state.wanted==='wantBin'?Convert(this.state.result,'setBin'):this.state.result;

return(

<div>

<InputBox title='Dec' callBack={this.callBack_changeDec} selfValue={result_titleIsDec}/>

<InputBox title='Bin' callBack={this.callBack_changeBin} selfValue={result_titleIsBin}/>

</div>

)

}

}

ReactDOM.render(<Main />, document.getElementById('root'));

【解析】

以上是 React十进制和二进制转换的实现和分析 的全部内容, 来源链接: utcz.com/z/382758.html

回到顶部