通常,一些组件需要反映相同的数据更改,这种情况推荐将共享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>
)
}
}

React——共享state的更多相关文章

  1. React:Lifting State Up

    在学习React的组件的时候,我也好奇组件间需要共享状态或通信的时候,React是如何处理的.在文档的QUICK START的提到Lifting State Up(状态提升),并不是什么新鲜东西.只是 ...

  2. react 中state与props

    react 中state与props 1.state与props props是只读属性,只有在组件被实例化的时候可以赋值,之后的任何时候都无法改变该值.如果试图修改该值时,控制台会报错 only re ...

  3. [React] Update State in React with Ramda's Evolve

    In this lesson we'll take a stateful React component and look at how we can refactor our setState ca ...

  4. React给state赋值的两种写法

    如果你看过React的官方文档,就会对怎么给局部state赋值有一定的了解.如下代码: class Test extends React.Component { constructor(props) ...

  5. Recoil & React official state management

    Recoil & React official state management Redux Recoil.js https://recoiljs.org/ A state managemen ...

  6. React & update state with props & Object.assign

    React & update state with props & Object.assign Object.assign({}, oldObj, newObj) https://re ...

  7. 七天接手react项目 —— state&事件处理&ref

    state&事件处理&ref 在 react 起步 一文中,我们学习了 react 相关知识:jsx.组件.props.本篇将继续研究 state.事件处理和ref. state St ...

  8. React组件State提升(译)

    译自:https://reactjs.org/docs/lifting-state-up.html (适当进行了裁减) 通常我们会碰到这样的情况,当某个组件的state数据改变时,几个React组件同 ...

  9. [React Fundamentals] State Basics

    State is used for properties on a component that will change, versus static properties that are pass ...

随机推荐

  1. 译-BMC Remedy Action Request System权限控制概述

    原文链接:Access control overview 说明: BMC Remedy Action Request System是BMC ITSM产品平台,简称AR 或者Remedy,可实现基于IT ...

  2. jdbc与java.sql

    JDBC连接操作数据库流程:1.将数据库驱动jar包放在lib文件夹下. 2.定义驱动名(driver),数据库url,username,password字符串常量 3.注册数据库驱动Class.fo ...

  3. android 弹起键盘把ui顶上去的解决办法

    键盘输入框上面的ui布局必须为Relative相对布局.然后设置 <activityandroid:name=".activity.HomeActivity"Android: ...

  4. PDO prepare预处理语句

    预处理语句 $dsn="mysql:host=localhost;dbname=emp"; try{ $pdo=new PDO($dsn,'root','root'); }catc ...

  5. SQL语句-SELECT语句

    select语句 Select语句是指从现存的一个或多个表中查看满足条件的数据 Select语句常规用法: 查看表中所有数据 Select * from students; 查看所有的sid和snam ...

  6. linux上的用户管理

    作为一个专业的服务器发行版,CentOS上存在着n多个用户,作为一个专业的运维工程师,linux的用户管理和用户组的管理是做为一个SA必不可少的工作. 下面我们就先来谈谈linux中的用户管理: us ...

  7. 全部用startssl生成的证书,配置Apache使其支持SSL

    Apache的编译安装见这篇: http://www.cnblogs.com/yjken/p/3921840.html 网上查阅了一大批资料,得知自己生成的证书是会被浏览器提示“证书不安全”的,我也就 ...

  8. mysql5.6默认情况下内存占用太大

    下载了mysql5.6.12 ,默认占用内存达400多M,  而原来使用的5.0 只有30M.. 解决方案:调整以下参数----------------performance_schema_max_t ...

  9. Linux下使用skipfish扫描网站漏洞步骤

    skipfish是谷歌开发的网站安全扫描工具. 下载地址:http://pan.baidu.com/s/1kTC66lL svn更新地址(一般链接不上,网速很慢): http://skipfish.g ...

  10. 【自适应辛普森积分】hdu1724 Ellipse

    Ellipse Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Sub ...