How to update parent's state in React?

后端 未结 14 1411
粉色の甜心
粉色の甜心 2020-11-22 08:48

My structure looks as follows:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 s

14条回答
  •  死守一世寂寞
    2020-11-22 09:25

    This the way I do it.

    type ParentProps = {}
    type ParentState = { someValue: number }
    class Parent extends React.Component {
        constructor(props: ParentProps) {
            super(props)
            this.state = { someValue: 0 }
    
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(value: number) {
            this.setState({...this.state, someValue: value})
        }
    
        render() {
            return 

    Value: {this.state.someValue}

    } } type ChildProps = { defaultValue: number, changeFunction: (value: number) => void} type ChildState = { anotherValue: number } class Child extends React.Component { constructor(props: ChildProps) { super(props) this.state = { anotherValue: this.props.defaultValue } this.handleChange = this.handleChange.bind(this) } handleChange(value: number) { this.setState({...this.state, anotherValue: value}) this.props.changeFunction(value) } render() { return
    this.handleChange(Number(event.target.value))} type='number' value={this.state.anotherValue}/>
    } }

提交回复
热议问题