简体   繁体   English

如何从 Material UI 为我的应用中的 React 添加带有 Back to Top 按钮的 AppBar?

[英]How do I add AppBar with Back to Top button from Material UI for React in my App?

In the documentation of Material UI, I found this code:在 Material UI 的文档中,我发现了这段代码:

import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import useScrollTrigger from '@material-ui/core/useScrollTrigger';
import Box from '@material-ui/core/Box';
import Container from '@material-ui/core/Container';
import Fab from '@material-ui/core/Fab';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';
import Zoom from '@material-ui/core/Zoom';

const useStyles = makeStyles((theme) => ({
    root: {
        position: 'fixed',
        bottom: theme.spacing(2),
        right: theme.spacing(2),
    },
}));

function ScrollTop(children) {
    const classes = useStyles();
    const trigger = useScrollTrigger({
        target: window ? window() : undefined,
        disableHysteresis: true,
        threshold: 100
    });

    const handleClick = (event) => {
        const anchor = (event.target.ownerDocument || document).querySelector('#back-to-top-anchor');
        if (anchor) {
            anchor.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    };
    return (<Zoom in={trigger}>
        <div onClick={handleClick} role="presetation" className={classes.root}>
            {children}
        </div>
    </Zoom>);
}
export default function BackToTop(children) {
    return (
        <React.Fragment>
            <CssBaseline />
            <AppBar>
                <Toolbar>
                    <Typography variant="h6">Scroll to see button</Typography>
                </Toolbar>
            </AppBar>
            <Toolbar id="back-to-top-anchor" />
            <Container>
                <Box my={2}>
                    {[...new Array(100)]
                        .map(
                            () => `Cras mattis consectetur purus sit amet fermentum.
                                    Cras justo odio, dapibus ac facilisis in, egestas eget quam.
                                    Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
                                    Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`,
                        )
                        .join('\n')}
                </Box>
            </Container>
            <ScrollTop {...children}>
                <Fab color="secondary" size="small" aria-label="scroll back to top">
                    <KeyboardArrowUpIcon />
                </Fab>
            </ScrollTop>
        </React.Fragment>
    );
}

There was said that this code is top bar, which will draw Back to top button.有人说这段代码是top bar,会画Back to top button。 But I don't understand what should I pass as children to BackToTop function.但我不明白我应该把什么作为children传递给BackToTop function。 Can anyone help me?谁能帮我?
PS Code also includes content, that is stored inside Box element, it is just for testing. PS Code 还包含内容,存储在Box元素中,仅用于测试。 If I understand purpose of children parameter right, I should have ability to make BackToTop function independent of any parameters.如果我理解children参数的目的,我应该有能力使BackToTop function 独立于任何参数。

The portion of the documentation you are referring to is here: https://material-ui.com/components/app-bar/#back-to-top .您所指的文档部分在这里: https://material-ui.com/components/app-bar/#back-to-top The code sandbox version of that demo is here: https://codesandbox.io/s/r59zg?file=/demo.js .该演示的代码沙盒版本在这里: https://codesandbox.io/s/r59zg?file=/demo.js

The code in your question has some problematic changes compared to the demo from the documentation.与文档中的演示相比,您问题中的代码有一些有问题的更改。 Confusingly, you have renamed props to children in a couple places ( BackToTop argument and ScrollTop argument).令人困惑的是,您在几个地方( BackToTop参数和ScrollTop参数)将props重命名为children级。 One thing to note in the code from the documentation is that the props passed to BackToTop are never used -- they are passed through to ScrollTop via <ScrollTop {...props}> , but ScrollTop doesn't use any of those props either (and since index.js doesn't pass any props to BackToTop , it is an empty object so there isn't much that could be done with it).文档代码中需要注意的一件事是,传递给BackToTop的道具从未使用过——它们是通过<ScrollTop {...props}>传递给ScrollTop的,但ScrollTop也不使用任何这些道具(并且由于index.js没有将任何道具传递给BackToTop ,它是一个空的 object 所以没有什么可以做的)。

Here is a slightly simplified version of the demo to remove the props that aren't used:这是一个稍微简化的演示版本,用于删除未使用的道具:

import React from "react";
import PropTypes from "prop-types";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import useScrollTrigger from "@material-ui/core/useScrollTrigger";
import Box from "@material-ui/core/Box";
import Container from "@material-ui/core/Container";
import Fab from "@material-ui/core/Fab";
import KeyboardArrowUpIcon from "@material-ui/icons/KeyboardArrowUp";
import Zoom from "@material-ui/core/Zoom";

const useStyles = makeStyles(theme => ({
  root: {
    position: "fixed",
    bottom: theme.spacing(2),
    right: theme.spacing(2)
  }
}));

function ScrollTop(props) {
  const { children } = props;
  const classes = useStyles();
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 100
  });

  const handleClick = event => {
    const anchor = (event.target.ownerDocument || document).querySelector(
      "#back-to-top-anchor"
    );

    if (anchor) {
      anchor.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  };

  return (
    <Zoom in={trigger}>
      <div onClick={handleClick} role="presentation" className={classes.root}>
        {children}
      </div>
    </Zoom>
  );
}

ScrollTop.propTypes = {
  children: PropTypes.element.isRequired
};

export default function BackToTop() {
  return (
    <React.Fragment>
      <CssBaseline />
      <AppBar>
        <Toolbar>
          <Typography variant="h6">Scroll to see button</Typography>
        </Toolbar>
      </AppBar>
      <Toolbar id="back-to-top-anchor" />
      <Container>
        <Box my={2}>
          {[...new Array(25)]
            .map(
              () => `Cras mattis consectetur purus sit amet fermentum.
Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`
            )
            .join("\n")}
        </Box>
      </Container>
      <ScrollTop>
        <Fab color="secondary" size="small" aria-label="scroll back to top">
          <KeyboardArrowUpIcon />
        </Fab>
      </ScrollTop>
    </React.Fragment>
  );
}

编辑回到顶部

The children being used in ScrollTop are the child elements in the JSX within the ScrollTop element. ScrollTop中使用的children元素是ScrollTop元素内 JSX 中的子元素。 In this case that is:在这种情况下是:

        <Fab color="secondary" size="small" aria-label="scroll back to top">
          <KeyboardArrowUpIcon />
        </Fab>

This is passing a floating-action-button to ScrollTop as the thing to show when the user scrolls and the thing that, when clicked on, will cause the page to scroll back to the top.这是将浮动操作按钮传递给ScrollTop ,作为用户滚动时显示的内容,以及单击时将导致页面滚动回顶部的内容。

The code in your question has ScrollTop(children) though instead of ScrollTop({children}) -- ie you are calling the entire props object children rather than getting the children prop out of it.您问题中的代码有ScrollTop(children)而不是ScrollTop({children}) - 即您正在调用整个props object children ,而不是让children摆脱它。

暂无
暂无

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

相关问题 如何在数据网格 Material-UI 中单击按钮时添加 React 组件? - How do I add React component on button click in Data Grid Material-UI? 如何在菜单顶部添加标题和关闭按钮(在 material-ui 中单击时,在按钮菜单中的第一项上方? - How do I add a title and close button to the top of a menu (above the 1st item in a button menu when clicked in material-ui? Material UI - 我的卡片组件正在添加到我的 Appbar。 我希望卡片在点击 Appbar 的按钮后显示 - Material UI- My Card Component is getting added to my Appbar. I want the cards to show up once a button the Appbar is clicked 如何添加一个条件来反应 material-ui 个元素? - How do I add a condition to react material-ui elements? 如何让我的 ScrollView 不回弹到顶部? (反应原生) - How do I keep my ScrollView from snapping back to the top? (React Native) 如何向Material-UI的AppBar组件添加多个元素? - How do you add multiple elements to Material-UI's AppBar component? "如何使 Material-ui-next 中的 AppBar 组件对滚动事件做出反应" - How to make AppBar component from material-ui-next react to scroll events 如何在React中自定义Material UI? - How do I customize Material UI in React? 如何将Facebook登录UI添加到我的React Native应用程序中? - How do I add the facebook login UI to my React Native app? 具有React Router 4实现的物料UI AppBar无法正常工作 - Material UI AppBar with React Router 4 Implementation not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM