简体   繁体   中英

Getting pagination button value with react-bootstrap Pagination component

I have a simple pagination similar to the react-bootstrap docs for Pagination . I do need to know which specific button was clicked, so I added data attributes to the Pagination.Item components. My data attribute is named "data-page".

Each key attribute for the pagination items must be unique, so that's why I felt it was necessary to have a data-page attribute.

<Pagination onClick={debugClick}>
  <Pagination.First key={0} data-page={1} />
  <Pagination.Item key={1} data-page={1}>
    {1}
  </Pagination.Item>
  <Pagination.Item key={2} data-page={2}>
    {2}
  </Pagination.Item>
  <Pagination.Item key={3} data-page={3}>
    {3}
  </Pagination.Item>
  <Pagination.Last key={4} data-page={3} />
</Pagination>

The problem is that when I click on one of the pagination buttons, there seems to be a difference if I click directly on the number or somewhere to the side of the number. I can see this in my onClick handler. I'm worried that this method of determining the data-page attribute is unreliable.

const debugClick = (e) => {
  const clickValue = e.target.offsetParent.getAttribute('data-page')
    ? e.target.offsetParent.getAttribute('data-page')
    : e.target.getAttribute('data-page');
  console.log( clickValue );
};

Notice how sometimes the attribute is inside offsetParent, but other times it is just directly inside the event target. I could also do this:

const debugClick = (e) => {
  const clickValue = e.target.tagName == 'SPAN'
    ? e.target.offsetParent.getAttribute('data-page')
    : e.target.getAttribute('data-page');
  console.log( clickValue );
};

For right now, in Linux desktop Firefox (untested on other devices and browsers) this seems to work fine, but I'm worried that this is going to break, because it doesn't seem like solid code. So I'm here to ask what's the proper way to deal with getting the value of my data-page attribute. How can I most reliably get the value in all browsers?

More info: I did see this issue , but I don't want to get the text inside the button. It would be a lot cleaner if I could get the value of my data attribute.

Pagination.Item should have onClick, not Pagination

<Pagination>
 <Pagination.Item key={1} onClick={(event) => this.paginationClicked(event)}>
   {1}
 </Pagination.Item>
 <Pagination.Item key={2} onClick={(event) => this.paginationClicked(event)}>
   {2}
 </Pagination.Item>
 <Pagination.Item key={3} onClick={(event) => this.paginationClicked(event)}>
   {3}
 </Pagination.Item>
</Pagination>

then you can access it via event.target.text

paginationClicked = (event) => {
  var itemClicked = event.target.text;
}

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