React学习之——状态提升
Posted 芜独独
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React学习之——状态提升相关的知识,希望对你有一定的参考价值。
React文档之状态提升链接链接: link.
状态提升:
在 React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享
实现一个华氏度和摄氏度的转换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
// 状态提升:
// 在 React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state。
// 定义键值对
const scaleNames =
c:'Celsius',
f:'Fahrenheit'
// 将华氏度转换为摄氏度
function toCelsius(fahrenheit)
return (fahrenheit - 32) * 5 / 9;
// 将摄氏度转换为华氏度
function toFahrenheit(celsius)
return (celsius * 9 / 5) + 32;
// 温度转换
function tryConvert(temperature,convert)
const input = parseFloat(temperature);
if (Number.isNaN(input))
return '';
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
// 判定水开了没有
function BoilingVerdict(props)
if (props.celsius >= 100)
return <p>The water would boil .</p>
return <p>The water would not boil</p>
// 温度输入组件
class TemperatureInput extends React.Component
constructor(props)
super(props);
this.handleChange = this.handleChange.bind(this);
// this.state = temperature:'';
handleChange(e)
// this.setState(temperature:e.target.value);
this.props.onTemperatureChange(e.target.value);
render()
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in scaleNames[scale]:</legend>
<input
value=temperature
onChange=this.handleChange
/>
</fieldset>
)
// 计算组件
class Caculator extends React.Component
constructor(props)
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = temperature:'',scale:'c';
handleCelsiusChange(temperature)
this.setState(scale:'c',temperature);
handleFahrenheitChange(temperature)
this.setState(scale:'f',temperature);
render()
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature,toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature,toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale='c'
temperature=celsius
onTemperatureChange=this.handleCelsiusChange />
<TemperatureInput
scale='f'
temperature=fahrenheit
onTemperatureChange=this.handleFahrenheitChange />
<BoilingVerdict
celsius=parseFloat(celsius) />
</div>
)
ReactDOM.render(<Caculator />,document.getElementById('root'))
</script>
</body>
</html>
效果截图
以上是关于React学习之——状态提升的主要内容,如果未能解决你的问题,请参考以下文章