简体   繁体   中英

How to call React forceUpdate() on the component that is defined in JSX component tree in render()

I have the React component with schematic code:

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> is some complex React component like https://devexpress.github.io/devextreme-reactive/react/grid/ or https://www.ag-grid.com/react-getting-started/ and its appearcance depends on some state variable. <Grid> is re-rendered automatically (eg its final, computed (by React) style is updated) if this.props.orders is updated. But I have this.state.selectedOrderNo variable which does not belong to the this.props.orders (of course, these are 2 different variables - array of props and scalar of state) and Grid has some styling rules that depend on this.state.selectedOrderNo but those styling rules are computed/rendered only when the <Grid> is rerendered (but this re-rendering does not happen when this.state.selectedOrderNo changes, because those styling rules are some deeper options than the direct parameters of the <Grid> ) but I would like to initiate this re-rendering of the Grid when this.state.selectedOrderNo is changed. So, that is why I am trying to call grid.forceUpdate() . But the question is - how can I get reference grid to the <Grid component> ?

You need to use ref in Grid to make it work

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>  
        );
}
}

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM