最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React trigger resize but don't actually resize the screen - Stack Overflow

programmeradmin2浏览0评论

I am trying to trigger a resize without actually resizing the screen as it fixes my slider.

  window.dispatchEvent(new Event('resize')); 

The code above does not work, does anybody have any other ways of triggering a resize in react?

Had to use jQuery:

jQuery(window).resize();

I am trying to trigger a resize without actually resizing the screen as it fixes my slider.

  window.dispatchEvent(new Event('resize')); 

The code above does not work, does anybody have any other ways of triggering a resize in react?

Had to use jQuery:

jQuery(window).resize();
Share Improve this question edited Oct 31, 2019 at 14:03 BennKingy asked Oct 31, 2019 at 13:49 BennKingyBennKingy 1,5933 gold badges26 silver badges54 bronze badges 3
  • 1 Can't you call the .onresize instead? – user5734311 Commented Oct 31, 2019 at 13:55
  • jQuery(window).resize(); - this worked Chris! – BennKingy Commented Oct 31, 2019 at 14:03
  • 1 Great, but I don't think you need to use jQuery. Try window.onresize(); instead. Also, please don't answer questions inside the question. If you're positive this isn't a duplicate of an existing question, post your answer as actual answer. (also note that this seems to be an xy problem, we should rather be fixing the slider) – user5734311 Commented Oct 31, 2019 at 14:11
Add a ment  | 

2 Answers 2

Reset to default 8

I think you take the issue in the wrong way.

You should never rely on resize during initial view.

So your slider code have an issue on sizing which is typical when dealing with images (read the width before the image is loaded).

But if you still want to try that way

It may be depends on where do you dispatch this event ? If you dispatch it before your Slider is renderered it will not work.

A solution could be to use React.useEffect:

function MySlider() {
  React.useEffect(() => {
    // dispatch it once mounted
    window.dispatchEvent(new Event('resize')); 
  }, []);
  return <div>Your stuff</div>
}

Stuck into the same problem for OpenLayer Map as well as D3 charts. Problem is Component didn't get mount when you dispatch that Window Resize Event. Workaround is to introduce delay while firing the event.

setTimeout(
()=>{window.dispatchEvent(new Event('resize'));},
2500
);

It should work.

发布评论

评论列表(0)

  1. 暂无评论