React——共享state
2024-10-09 16:25:46
通常,一些组件需要反映相同的数据更改,这种情况推荐将共享state移动到它们最近的公共祖先上。
在这里有一个例子:有一个温度计算器计算在给定温度是否能让水沸腾,用户可以输入华氏温度也能输入摄氏温度,当改变一种温度时另一种温度也要跟着改变
在这里摄氏温度输入框的值与华氏温度输入框的值要相互关联,所以这两个输入框都引用了同一个状态,所以这个共享的状态要位于他们最近的公共祖先上。具体代码如下:
// 温度输入组件
class TemperatureInput extends React.Component{
handleChange(event){
this.props.change(this.props.scale,event.target.value);
}
render(){
return <p>
<label>{this.props.scale === 'c' ? '摄氏温度' : '华氏温度'}:</label>
<input type='text' value={this.props.value} onChange={this.handleChange.bind(this)}/>
</p>
}
}
// 显示是否沸腾的组件
class ShowBoil extends React.Component{
render(){
if(this.props.temperature >= 100){
return <p>The water would boil</p>
} else {
return <p>The water would not boil</p>
} }
}
// 温度计算组件
class Calculator extends React.Component{
constructor(props){
super(props);
this.state = {
scale:'c',
temperature:''
};
}
changeState(scale,temperature){
this.setState({scale,temperature});
}
covertTemperature(scale,temperature){
if(Number.isNaN(parseFloat(temperature))){
return ''
}
// 把摄氏温度转换为华氏温度
if(scale === 'c'){
return ((temperature * 9 / 5) + 32) + '';
}
// 将华氏温度转换为摄氏温度
else {
return ((temperature - 32) * 5 / 9 ) + '';
}
}
render(){
const scale = this.state.scale;
const temperature = this.state.temperature;
const cTemperature = scale === 'f'?this.covertTemperature(scale,temperature):temperature;
const fTemperature = scale ==='c'?this.covertTemperature(scale,temperature):temperature;
return (
<div>
<TemperatureInput change={this.changeState.bind(this)} value={cTemperature} scale='c'/>
<TemperatureInput change={this.changeState.bind(this)} value={fTemperature} scale='f'/>
<ShowBoil temperature={cTemperature}/>
</div>
)
}
}
最新文章
- [转]caffe的配置过程
- 5.15[没什么营养的一段日子]A*
- 一个LINUX狂人的语录(个人认为很精辟)
- CF 445A 简单DP
- Myeclipse 快捷键设置和自动提示设置
- nutch 生产者队列的大小如何控制 threadcount * 50
- poj 1328 Radar Installation【贪心区间选点】
- [转]Windows中的命令行提示符里的Start命令执行路径包含空格时的问题
- bzoj3668
- Linux操作数据库基本
- vs2017使用问题
- Jenkins自定义变量共享
- (Android系统目录结构)目录预览
- Linux常用基本命令:三剑客命令之-awk动作用法(1)
- oracle 年龄计算 岁 月 天
- oracle jdbc jar 的一些说明
- PHP扩展的基本结构
- thinkphp 3.2.3 addAll方法的坑
- MySQL/MariaDB学习笔记——mysql.user表中存在多个root用户问题理解
- @RequestParam注解的作用
热门文章
- 译-BMC Remedy Action Request System权限控制概述
- 用SecureCRT来上传和下载文件
- getRequestDispatcher()和response.sendRedirect()
- 一个ios的各种组件、代码分类,供参考
- text和submit框的border问题
- tomcat调优(三)
- 用记事本编写java中的HelloWorld
- java.lang.String中[ ";张飞";+1+1 ] 和 [ ";张飞";+(1+1) ]
- 【分布式】ZooKeeper学习之一:安装及命令行使用
- Spring整合quartz框架实现任务定时调度