當一個子組件需要改修父組件傳來的props時候(想了一下的確有這種場景),可以在初始化的時候賦值給自己的 stateconstructor (props) { this.state = {
foo: props.foo
}
}然后在組件內部操作 state, 但是如果遇到父組件更新 props, 那么子組件的 constructor 是不會再調用的,那么就要這么寫componentWillReceiveProps (nextProps) { this.setState({ foo: nextProps.foo })
}這樣寫是不是有點麻煩,還是我沒有理解其中的真諦。
react subcomponent 如何修改 props?
慕碼人2483693
2019-02-26 20:17:28