react状态提升理解

状态提升,就是react帮我们把多个组件需要用到的数据,提升到最近的父组件中统一管理并传给子组件。
各个组件只能管理自己的状态。提升到父组件之后,子组件的就只能使用父组件传过来的props进行渲染,不能控制。
react是自上而下的数据流。并且所有的数据源都在父组件,方便了我们对于bug的排查。

官网的例子有点散,不是很直观,下面根据官网的例子写的一个简单的demo。官网传送门;

项目创建是用create-react-app,不会的看这里

home.js

import React, { Component } from "react";
import Header from '../../component/header/header.js';
import Footer from '../../component/footer/footer';
import Sidebar from '../../component/sidebar/sidebar';

class Home extends Component {
    constructor(props) {
        super(props)

        // strs 为状态提升的唯一数据来源
        this.state = {
            strs: '',
        }
    }

    changeData = (strs) => {
        this.setState   ({
            strs,
        })
    }

    render () {        
        return (
            <div className="test_home">
                <Header str={ this.state.strs.toUpperCase() } handleChangeValue={ this.changeData.bind(this) }/>
                <Header str={ this.state.strs.toLowerCase() } handleChangeValue={ this.changeData.bind(this) }/>               
            </div>
        )
    }
}

export default Home 

header.js

import React, { Component } from "react";

class Header extends Component{
    constructor(props){
        super(props);        
        this.state = {
        }
    }

    componentDidMount () {
        console.log(this.props);
    }

    
    inpChange = (e) => {
        this.props.handleChangeValue(e.target.value)
    }


    render () {
        return (
            <div>
                { this.props.title }
                <input value={ this.props.str } onChange={ this.inpChange.bind(this)}/>
            </div>
        )
    }
}

export default Header;

home为渲染内容的页面组件,header为input组件。这里实现的效果是在通过header渲染的两个输入框,上面的输入框显示大写字母,下面的输入框显示小写字母,在任意一个输入框输入字母,两个输入框都能都能将值通过onChange触发propshandleChangeValue事件,触发父组件changeData事件来更新父组件的state strs。再将值经过处理渲染到2个子组件。


效果展示:在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值