--- title: 状态提升 (共享状态) date: 2021-03-26 09:56:40 permalink: /pages/f0e3d2/ categories: - 《React》笔记 - 核心概念 tags: - React author: name: xugaoyi link: https://github.com/xugaoyi --- # 09. 状态提升 (共享状态) 通常,**多个组件需要反映相同的变化数据,这时我们建议将共享状态提升到最近的共同父组件中去**。 在 React 中,**将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state。这就是所谓的“状态提升”** 两个输入框共享数据的例子: ```jsx const scaleNames = { c: '摄氏度', f: '华氏度' }; // 转摄氏度 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); // Math.round返回一个数字四舍五入后的整数 const rounded = Math.round(output * 1000) / 1000; return rounded.toString(); } // 水是否会沸腾 function BoilingVerdict(props) { if (props.celsius >= 100) { return
水会沸腾.
; } return水不会沸腾.
; } // 子组件 - 输入框 class TemperatureInput extends React.Component { constructor(props) { super(props); // 接收父组件传入props this.handleChange = this.handleChange.bind(this); // 绑定回调函数,并修正this } // 处理change handleChange(e) { // e是合成事件对象,通过e.target.value 取值 // 调用父组件传入的onTemperatureChange函数,并传值 this.props.onTemperatureChange(e.target.value); // 当子组件输入框值改变时调用父组件的onTemperatureChange方法,并传出值。 // 另外,onTemperatureChange命名方式:`在<子组件>变更` } render() { // 接收父组件传入的温度值 const temperature = this.props.temperature; // 接收父组件传入的衡量方式 const scale = this.props.scale; return ( ); } } // 父组件 - 计算器 class Calculator extends React.Component { constructor(props) { super(props); // 接收父组件传入props // 绑定事件回调,并修正this this.handleCelsiusChange = this.handleCelsiusChange.bind(this); this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this); // 创建初始状态值 this.state = {temperature: '', scale: 'c'}; } // 处理`摄氏度`变更 handleCelsiusChange(temperature) { // temperature接收到子组件传来的参数,并通过setState修改状态 this.setState({scale: 'c', temperature}); } // 处理`华氏度`变更 handleFahrenheitChange(temperature) { // temperature接收到子组件传来的参数,并通过setState修改状态 this.setState({scale: 'f', temperature}); } // 渲染函数(每当state改变都会调用) render() { // 取得当前state下的值 const scale = this.state.scale; const temperature = this.state.temperature; // 根据scale值取得相应的温度数据 const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature; const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature; // 返回渲染的元素 // 插入子组件TemperatureInput传入相应的参数,onTemperatureChange指定为当前组件的回调函数 return (