繁体   English   中英

如何在render()的JSX组件树中定义的组件上调用React forceUpdate()

[英]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.

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