简体   繁体   English

如何在反应中设置子组件的状态?

[英]How to set state of a childcomponent in react?

In my React component called Grid.js I am using a childcomponent called Pagination. 在名为Grid.js的React组件中,我使用的是名为Pagination的子组件。 It looks like this: 看起来像这样:

 <StyledBox wrap py={12} px={18}>
    <Header />
     {state.data}
    <Wrapper column justify="center" align="center" p={12}>
      <Pagination onChange={this.handleChange} totalPages={10} />
    </Wrapper>
  </StyledBox>

It is a grid with some pagination functionality. 它是具有某些分页功能的网格。 When the user selects a page on the Pagination a changeevent will fire and a stateprop of the Grid will be set called state.data. 当用户在分页中选择页面时,将触发changeevent并将设置Grid的stateprop,称为state.data。 The issue is that the pagination starts jumping around randomly: looks like the state has changed on the component. 问题是分页开始随机跳动:看起来组件的状态已经改变。

Do I have to move the Pagination out of the Grid component and make it not a childcomponent? 我是否必须将分页移出Grid组件并使其不成为子组件?

Is the Pagination Component jumping around randomly because previously there was a specific length of data. 分页组件是否由于先前存在特定长度的数据而随机跳动? Then when the this.state.data changes, the length of data is different? 那么当this.state.data更改时,数据长度是否不同? So then, the Pagination had to adjust it's positioning. 因此,分页必须调整其位置。 Without more information, it seems like a HTML and CSS issue. 没有更多信息,这似乎是HTML和CSS问题。

Try to set position: fixed; bottom: 1rem 尝试设定position: fixed; bottom: 1rem position: fixed; bottom: 1rem on the Pagination component css and see if it still jumps. position: fixed; bottom: 1rem分页组件css上的position: fixed; bottom: 1rem ,看看它是否仍然跳。

Also, regarding React Components, <Content /> and <Pagination /> components seem to be conceptually sibling and not parent-child related . 另外,对于React组件, <Content /> and <Pagination /> components seem to be conceptually sibling and not parent-child related So I would structure the app something like this: 所以我将构建这样的应用程序:

<ParentContainer>
  <Header />
  <Content data={this.state.data} />
  <Pagination onChange={this.handleChange} totalPages={10} />
</ParentContainer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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