简体   繁体   中英

Updating an ID tag on scroll React.js

You can find my project here: https://codesandbox.io/s/franchise-bg-effect-obd55

I am trying to match an array of CSS background ID tags ( bgArr ) to an array of each section ( destination.index ) in afterLoad() . So section 1 should have the ID of 'red', section 2 ID of 'blue', and section 3 ID of 'green'. On page load, section 1 has the correct ID tag of 'red'. When scrolling to section 2, in the console you will notice that bgIndex updates to the correct ID tag of 'blue' but the ID of the div on the page remains red. I'm not sure how to re-render the div with the updated ID tag.

I think instead of this:

afterLoad(origin, destination, direction) {
  this.setState({
    isLeaving: false,
  });

  bgIndex = bgArr[destination.index];
}

you should do this:

afterLoad(origin, destination, direction) {
  bgIndex = bgArr[destination.index];

  this.setState({
    isLeaving: false,
  });
}

If you change bgIndex after the setState call, the rerender might have already finished before bgIndex is updated to its correct value.

Sandbox Example

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