状态提升,就是
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
触发props
的handleChangeValue
事件,触发父组件changeData
事件来更新父组件的state
strs
。再将值经过处理渲染到2个子组件。
效果展示: