React学习笔记(11)状态提升

2019-09-29  本文已影响0人  nieniemin

通常,多个组件需要反映相同的变化数据,这时我们建议将共享状态提升到最近的共同父组件中去。

两个组件都要用到同一个数据或者说是状态,因此为了保证两个组件都能正常使用该数据或者状态,将该数据提升到两个组件最近的公共父节点进行保管,然后通过props将该数据传到组件中,这样就可以在组件中共享数据了。
官方文档通过温度计转换,下面实现一个类似的效果。通过中美汇率转换demo,将共同状态输入金额提升到父级中管理。
1.子组件Children.jsx

import React from 'react';

export default class Children extends React.Component {

    handlerChange(event) {
        // 子组件传值给父组件中的getChildrenProps属性。
        this.props.getChildrenProps(event.target.value);
    }
    render () {
        const type = this.props.type === 'dollar' ? '美元':'人民币';
        return (
            <fieldset>
             <legend>{type}</legend>
             <input value={this.props.money} onChange={this.handlerChange.bind(this)} />
            </fieldset>
          );
    }

}
  1. 父组件Parent.jsx
import React from 'react';
import Children from './Children';

export default class Parent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dollar:'',
            yuan:'',
        };
    }

    handlerDollarChange(value) {
        this.setState({
            dollar: value,
            yuan: value * 7.1543
        });
    }

    handlerYuanChange(value) {
        this.setState({
            dollar:  value * 0.1398,
            yuan: value,
        });
        
    }
    render () {
        return (
            <div>
             <Children type={'dollar'} money={this.state.dollar}  getChildrenProps = {this.handlerDollarChange.bind(this)}/>
             <Children type={'dyuanollar'} money={this.state.yuan} getChildrenProps = {this.handlerYuanChange.bind(this)}/>
            </div>
          );
    }
}
上一篇 下一篇

猜你喜欢

热点阅读