React随笔

324 阅读1分钟

React中的状态提升

React中的状态提升概括来说,就是将多个组件需要共享的状态提升到它们最近的父组件上.在父组件上改变这个状态然后通过props分发给子组件.

import React from 'react'
class A extends React.Component{
     constructor(props){
         super(props)
     }
    render(){
        return (
            <div>
                <h1>{this.props.value+1}</h1>
            </div> 
        )
    }
}
class B extends React.Component{
     constructor(props){
         super(props)
     }
    render(){
        return (
            <div>
                <h1>{this.props.value+2}</h1>
            </div> 
        )
    }
}
class App extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            txt:"阿巴"
        }
        this.handleChange = this.handleChange.bind(this)
    }
    handleChange(e){
        this.setState({
            txt:e.target.value
        })
    }
    render(){
       return (
            <div>
                <input type="text" value={this.state.txt} onChange={this.handleChange}/>
                <p>{this.state.txt}</p>
                <A value={this.state.txt}/>
                <B value={this.state.txt}/>
            </div>
       )
    }
}
export default App