Scrollview react native не работает

ScrollView.scrollTo method not working #24531

Comments

valentinacala commented Apr 19, 2019 •

🐛 Bug Report

Hi all,
I’m experiencing issues with the method «scrollTo» on the ScrollView component.
I applied the same approach on a FlatList component (using the scrollToIndex method) and it works, while any other try on scrollView fails.

Expected Behavior

Using react-navigation, I expect the list scrolls to the first item every time I return on the screen from another screen. Trying it, the component doesn’t scroll to the first item.

Code Example

Environment

React Native Environment Info:
npmPackages:
react: 16.8.3
react-native: 0.59.3

The text was updated successfully, but these errors were encountered:

JKCooper2 commented Apr 19, 2019

Can you confirm the scrollToTop is being fired and that the ref exists when you do call it.

My guess is the scrollToTop is being fired before the element is initially rendered and so the dom element isn’t available to do anything. One way to check is to wrap the scrollTo call in a setTimeout of 500ms and seeing if it works correctly then. If it does it mean you need to change your code logic rather than it being a bug.

valentinacala commented Apr 24, 2019

@JKCooper2 thank you for your answer. Actually, I found that the problem was related to the fact that my ScrollView was placed as child of a Content tag and the scroll behaviour I experienced was related to it instead of my scrollView.

Thank you and Regards!

bhavinwebdesk commented Jul 11, 2019

@valentinacala scrollTo working for you in Android?

valentinacala commented Jul 11, 2019

Hi @bhavinwebdesk , as mentioned, I solved the issue and it is worked as expected

Monte9 commented Jul 19, 2019

hmm.. I am running into this after I upgraded to v0.59. 🤔

Louis345 commented Aug 6, 2019

@Monte9 I am also. Any idea on how you resolved it?

msageryd commented Aug 14, 2019 •

I went from 0.57 to 0.60.4 and my previously working scrollTo-code stopped working (iOS).

Читайте также:  Как отремонтировать робот пылесос ilife

I can confirm that my scroll function is being called with correct parameters, but nothing happens.

I also tried to set scrollEnabled= which correctly let me scroll manually via touch, but scrollTo still doesn’t work.

Louis345 commented Aug 14, 2019

@msageryd I have been trying to have this issue looked at with no help. I created a StackOverFlowPost here https://stackoverflow.com/questions/57385037/react-natives-animated-scrollview-is-not-allowing-me-to-programmatically-scroll. I even went as far as to offer a bounty to no avail. I think this ticket needs to be reopened again.

msageryd commented Aug 14, 2019

It seems like something has changed with the timing for mounting stuff (between RN versions). I will go through my code again (in a couple of days), as I suspect that I’m using some of the soon-to-be deprecated lifecycle functions. The fact that they are now considered «unsafe» to use might be due to some timing issues (wild guess).

I got my code to work by simply putting the scrollTo in a 100ms timeout. This indicates that the scrollview is not quite mounted at the first try. I’m actually fine with the timeout for my use case, but I want to solve this anyway because I don’t like hacky solutions.

Louis345 commented Aug 14, 2019

@msageryd thank you for this. It will help me finally upgrade. If you want, you can respond my to question on StackOverflow, so I can give you some bounty points.

sftgf commented Aug 20, 2019 •

I couldn’t get this to work even with adding a timeout. Did you find a way to make it work, @Louis345 ?

Источник

React Native ScrollView is not working in iOS

I am working through a tutorial on React-Native. When I tried to instantiate a ScrollView inside of my app it doesn’t work. There are no errors, no red screen, it simply won’t scroll past the second of five elements.

Here is the code for my index.ios.js

Here is the code for the component AlbumList

And finally, here is the code for the AlbumDetail component.

Any help would be greatly appreciated.

3 Answers 3

If anyone is falling over this. Make sure that the ScrollView Container does have a height as mentioned by @SomethingOn . Furthermore I resolved it for ios by using TouchableWithoutFeedback wrapped around each item. Just give each one a key and leave onPress empty.

This was it for me at the end:

If you are using a trackpad and are trying to scroll with two fingers, try to scroll by pressing one finger and dragging with another finger.

I’m running into a similar problem and it seems related to the ScrollView not knowing the height of it’s Children. Try setting a height on the component in the AlbumDetail’s render method. The documentation for the ScrollView component makes reference to this, but it’s a little confusing. especially the part about flex :1.

Читайте также:  Платформа java не работает

My problem is that I’m dynamically loading ScrollView children and therefore I don’t know how to tell the scroll view that it has X children and therefore it’s height is Y.

Источник

React-Native, Scroll View Not Scrolling

When I wrap content like this example below, it scrolls Perfectly..

However, whenever I wrap it in another View, It will not scroll.

Is there some sort of fix to this. I am trying to put a nav bar header above all of the content, couldn’t really figure it out though.

10 Answers 10

It’s a typo:
Your closing ScrollView tag is: rather than . You also need to add a style to the View container, here’s an example of what it should look like:

Try adding style=<> to and components. You also have a typo on your code: in line 9. An example code will look like this:

Another solution is to add a height property to the parent View container. This sometimes works well when calculating the height against the screen height.

If your ScrollView is within something that handles touch ( Pressable , TouchableWithoutFeedback etc) then you either need to stop the touch event propagating up to that parent handler or else the ScrollView won’t handle the touch event and therefore won’t scroll.

This can be done either with onStartShouldSetResponder= <() =>true> or by wrapping the children in an element which itself handles the touch event (e.g. Pressable ):

Set nestedScrollEnabled as true for Hybrid Android + react app as it might be issue with gesture/click for scrolling issue.

I think the best way of doing this is to put all requires inside an array and map this array.

note that if you want it as a background image with other elements above the image, you may use BackgroundImage and either render elements for each image or position absolute the image map and zIndex it behind all things

I had a similar issues, it got solved by removing height/width if set to ‘100%’.

Just adding here if someone faces the same issues. 😀

Not the answer you’re looking for? Browse other questions tagged react-native or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.15.40479

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

React Native ScrollView не прокручивается внизу

внутри моего приложения index.io.js есть только 1 ScrollView , который завернут внутри View под функцию render . Иногда я могу прокручивать до самого конца ScrollView и удерживать экран там. Однако ScrollView вернется в верхнюю часть экрана и не сможет оставаться внизу внизу.

Кто-нибудь знает, что происходит? Благодарю.

p.s: мой RN равен 0.28.0, цель развертывания iOS — 8.0

Читайте также:  Не работает звуковой сигнал ниссан примера р12

ОТВЕТЫ

Ответ 1

Для React родных новичков вроде меня:

поиск ошибки установки в атрибуте scrollview contentContainerStyle , который в основном говорит прокруткуview явно не для прокрутки и ожидания ее прокрутки, поскольку это устанавливает высоту содержимого в один и тот же родительский кадр, который является scrollview

Ответ 2

Чтобы точно ответить на вопрос, ScrollView также должен иметь стиль = <> prop. Для прокрутки ScrollView требуется высота набора.

Однако в моем случае у меня было дополнение в моем представлении прокрутки, и это, должно быть, выбросило некоторые вычисления в глубину системы. Я использую реакцию native 0.55.

Чтобы решить, мне нужно было изменить:

Ответ 3

Имейте в виду, что ScrollViews должны иметь ограниченную высоту для работы, поскольку они содержат детей с неограниченной высотой в ограниченном контейнере (через взаимодействие с прокруткой). Чтобы связать высоту ScrollView, либо установите высоту представления напрямую (обескуражен), либо убедитесь, что все родительские представления имеют ограниченную высоту. Забыв передать вниз, стек представлений может привести к ошибкам здесь, которые инспектор элементов легко отлаживает.

Я думаю, вам следует назначить стиль вашему scrollView с свойством flex: 1. И создайте contentContainerStyle, чтобы иметь лучший дизайн.

Ответ 4

Добавление дополнительного бесполезного вида внизу scrollView:

решил мою проблему.

Ответ 5

использование flex: 1

Ответ 6

Когда вы используете в native реагировать, используйте flexGrow вместо flex. Если вы хотите получить более подробное руководство по этой причине, ознакомьтесь со статьей ниже:

Ответ 7

Раствор проверен на реакцию 0,57

IDK, исправили ли вы проблему, но это решение помогло мне

Не нужно ничего сгибать. Это спокойствие кода будет генерировать представление с желобом на всех 4 сторонах. И круто то, что последний элемент не обрезается.

Я очень ленив, чтобы добавить маршрутизатор, поэтому я добавил компонент панели приложений, чтобы добавить некоторое поле вверху для основного контента. Компонент панели приложения можно безопасно игнорировать.

Ответ 8

поэтому применение paddingBottom с определенным размером должно решить это за вас

Источник

FlatList inside ScrollView doesn’t scroll

I’ve 4 FlatList s with maxHeight set to 200 inside a ScrollView .

and when I try to scroll a FlatList , it doesn’t scroll but the ScrollView scrolls. How do I fix this issue ?

Full Source Code

7 Answers 7

We can use the built-in nestedscrollenabled prop for the children FlatList/ScrollView components.

This is only required for Android (Nested scrolling is supported by default on iOS).

I was having a very similar issue until I came across an almost complete solution in a very helpful comment on one of the GitHub issues for the react-native project: https://github.com/facebook/react-native/issues/1966#issuecomment-285130701.

The issue is that the parent component is the only one registering the scroll event. The solution is to contextually decide which component should actually be handling that event based on the location of the press.

You’ll need to slightly modify your structure to:

The only thing I had to change from the GitHub comment was to use this._myScroll.contentOffset instead of this.refs.myList.scrollProperties.offset .

I’ve modified your fully working example in a way that allows scrolling of the inner FlatLists.

Источник

Оцените статью