简体   繁体   English

在滚动 React.js 上更新 ID 标签

[英]Updating an ID tag on scroll React.js

You can find my project here: https://codesandbox.io/s/franchise-bg-effect-obd55你可以在这里找到我的项目: 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() .我正在尝试将 CSS 背景 ID 标签 ( bgArr ) 的数组与afterLoad()中每个部分的数组 ( destination.index ) 匹配。 So section 1 should have the ID of 'red', section 2 ID of 'blue', and section 3 ID of 'green'.所以第 1 部分的 ID 应该是“红色”,第 2 部分的 ID 应该是“蓝色”,第 3 部分的 ID 应该是“绿色”。 On page load, section 1 has the correct ID tag of 'red'.在页面加载时,第 1 部分具有正确的 ID 标签“红色”。 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.滚动到第 2 部分时,在控制台中,您会注意到bgIndex更新为正确的 ID 标签“蓝色”,但页面上 div 的 ID 仍为红色。 I'm not sure how to re-render the div with the updated ID tag.我不确定如何使用更新的 ID 标签重新渲染 div。

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.如果在setState调用之后更改bgIndex ,则重新渲染可能在bgIndex更新为正确值之前已经完成。

Sandbox Example 沙盒示例

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

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