[英]How to call React forceUpdate() on the component that is defined in JSX component tree in render()
我有帶有原理圖代碼的React組件:
class OrderList extends Component {
constructor() {
super();
this.handleUpdate = this.handleUpdate.bind(this);
}
handleChange(event) {
//>>POI how to get reference to the Grid, that is defined in the component tree?
//grid.forceUpdate();
}
render() {
return (
<div>
<Grid data={this.props.orders}>
<button onClick={this.handleUpdate}>Update</button>
</div>
);
}
}
<Grid>
是一些復雜的React組件,例如https://devexpress.github.io/devextreme-reactive/react/grid/或https://www.ag-grid.com/react-getting-started/ ,其外觀取決於在一些狀態變量上。 如果this.props.orders
被更新,則<Grid>
將自動重新渲染(例如,更新其最終的,通過React計算的樣式)。 但是我有this.state.selectedOrderNo
變量,它不屬於this.props.orders
(當然,這是2個不同的變量this.props.orders
數組和state的標量),並且Grid具有一些依賴於this.state.selectedOrderNo
樣式規則。 this.state.selectedOrderNo
但僅在重新渲染<Grid>
時才計算/渲染這些樣式規則(但是,當this.state.selectedOrderNo
更改時,不會進行此重新渲染,因為這些樣式規則比<Grid>
),但是當this.state.selectedOrderNo
更改時,我想重新初始化Grid。 因此,這就是為什么我嘗試調用grid.forceUpdate()
。 但是問題是- 如何獲得<Grid component>
參考grid
<Grid component>
?
您需要在Grid中使用ref
使其起作用
class OrderList extends Component {
constructor() {
super();
this.handleUpdate = this.handleUpdate.bind(this);
}
handleChange(event) {
//>>POI how to get reference to the Grid, that is defined in the component tree?
//grid.forceUpdate();
this.grid.forceUpdate();
}
render() {
return (
<div>
<Grid ref={ref=>this.grid=ref} data={this.props.orders}>
<button onClick={this.handleUpdate}>Update</button>
</div>
);
}
}
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.