父组件在应用栏和绘图区中包含一个按钮(我在其中拖放了一些内容,这仅适用于此处的上下文)。 我想让子组件保持相对独立。
我想在单击此父组件中可用的按钮时更改子组件的状态。 当我使用不安全的“componentWillReceiveProps”时它起作用(并且替换功能“很少使用”。 所以我从来没有成功地从父组件调用函数(在子组件中)。
React 中的最佳实践是什么?(我来自 PHP/GO/Python 背景)。
父类:
Class EditionView extends React.Component {
constructor(props) {
super(props)
var drawingModel = this.emptyDrawingModel();
this.state= {drawingModel:drawingModel};
}
emptyDrawingModel(){
var drawingModel = []
for (var i=0; i<3; i++) {
drawingModel.push('')
}
return drawingModel;
}
resetDrawingArea() {
console.log("tmp:", this);
var drawingModel = this.emptyDrawingModel();
this.setState({drawingModel: drawingModel});
}
render() {
console.log(this.state);
return (
<div>
<AppBar position="static" color="primary">
<Typography variant="h6" color="inherit">
Title
</Typography>
<Toolbar>
<Button variant='contained' component='span' onClick={()=>{this.resetDrawingArea()}}>Reset</Button>
</Toolbar>
</AppBar>
<Grid container>
<Grid item sm={9}>
<DrawingArea id='drawing' initialModel={this.state.drawingModel}/>
</Grid>
</Grid>
</div>
);
}
}
export default EditionView;
子类
class DrawingArea extends React.Component {
constructor(props) {
super(props)
this.state = {content:props.initialModel};
//this.reset = this.reset.bind(this);
//this.reset = this.reset();
}
/*
//WORKs but UNSAFE
componentWillReceiveProps(){
console.log("componentWillMount", this)
this.setState({content: this.props.initialModel});
}
*/
reset(){
console.log('in Drawing Area > reset')
var model = this.props.initialModel;
this.setState({content:model})
}
render() {
console.log("render drawing area", this)
var items = this.state.content.map((val, i) =>{
var item;
if (val === ''){
// code for if
} else {
// code for else
}
return item;
});
return(
<div id="main-area">
<Grid container>{items}</Grid>
</div>
)
}
}
export default DrawingArea;
最佳答案
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
class DrawingArea extends React.Component {
static getDerivedStateFromProps(props) {
return {
content: props.initialModel
}
}
...
}
关于javascript - 从父组件修改子状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087079/