【问题标题】:In Next.js, how to scroll to top of window after setting search value on a search bar?在 Next.js 中,如何在搜索栏上设置搜索值后滚动到窗口顶部?
【发布时间】:2020-11-23 08:45:22
【问题描述】:

想象一下我在某处有一个按钮。单击时,上面的文本现在转到我的搜索栏。在下面显示的Input 元素中设置值后,如何使窗口也滚动到搜索栏?

          <Flex
            flexDirection="column"
            justifyContent="center"
            alignItems="center"
            maxWidth="90%"
            mt={4}
          >
            {!filteredBlogPosts.length && 'No posts found.'}
            {filteredBlogPosts.map((frontMatter) => (
              <>
              <BlogPost
                key={frontMatter.title + frontMatter.lastPublishedOn}
                 handleSearch={(anyKey) => setSearchValue(anyKey)}
                 // Insert your code here, how to scroll after setting the key to search? 
                {...frontMatter}
              />
              </>
            ))}
          </Flex>

还有,这里是 &lt;Input&gt; 字段

            <Input
              aria-label="Search"
              borderColor="blue.500"
              onChange={(e) => setSearchValue(e.target.value)}
              placeholder="Search"
              value={searchValue}
              //or should I do scroll here? How?
              autoFocus
              onFocus={e => e.currentTarget.select()}
            />

这很容易做到吗?如果可能,请提供代码示例。

谢谢。

【问题讨论】:

    标签: reactjs search input scroll next.js


    【解决方案1】:

    如果以后有人遇到这个问题,我用这个简单的函数解决了。

        const scrollSearch = myKey => {
        window.scrollTo(0, 0);
        frontMatter.handleSearch(myKey)
      };
    

    并在按钮onClick中传递了scrollSearch函数。

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2012-08-04
      • 2017-11-24
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多