首页 > 解决方案 > 在 React 16 中不推荐使用“this.refs”时如何使用“mainPanel”?

问题描述

我有一个Dashboard.js

这是我的代码

import React from "react";
import cx from "classnames";
import PropTypes from "prop-types";
import {Switch, Route, Redirect, withRouter} from "react-router-dom";
import {browserHistory} from 'react-router';
// creates a beautiful scrollbar
import PerfectScrollbar from "perfect-scrollbar";
import "perfect-scrollbar/css/perfect-scrollbar.css";

// @material-ui/core components
import withStyles from "@material-ui/core/styles/withStyles";

// core components
import Header from "components/Header/Header.jsx";
import Footer from "components/Footer/Footer.jsx";
import Sidebar from "components/Sidebar/Sidebar.jsx";

import dashboardRoutes from "routes/dashboard.jsx";

import appStyle from "assets/jss/material-dashboard-pro-react/layouts/dashboardStyle.jsx";

import image from "assets/img/sidebar-2.jpg";
import logo from "assets/img/logo-white.svg";

const switchRoutes = (
  <Switch>
    {dashboardRoutes.map((prop, key) => {
      if (prop.redirect)
        return <Redirect from={prop.path} to={prop.pathTo} key={key}/>;
      if (prop.contain && prop.views)
        return prop.views.map((prop, key) => {
          return (
            <Route path={prop.path} component={prop.component} key={key}/>
          );
        });
      if (prop.collapse && prop.views)
        return prop.views.map((prop, key) => {
          if (prop.contain && prop.views)
            return prop.views.map((prop, key) => {
              return (
                <Route path={prop.path} component={prop.component} key={key}/>
              );
            });
          return (
            <Route path={prop.path} component={prop.component} key={key}/>
          );
        });
      return <Route path={prop.path} component={prop.component} key={key}/>;
    })}
  </Switch>
);

var ps;

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mobileOpen: false,
      miniActive: false,
      logged_in: localStorage.getItem('token') ? true : false,
    };
    this.resizeFunction = this.resizeFunction.bind(this);
  }

  componentDidMount() {
    if (!this.state.logged_in) {
      browserHistory.push("/accounts/login");
    }
    if (navigator.platform.indexOf("Win") > -1) {
      ps = new PerfectScrollbar(this.refs.mainPanel, {
        suppressScrollX: true,
        suppressScrollY: false
      });
      document.body.style.overflow = "hidden";
    }
    window.addEventListener("resize", this.resizeFunction);
  }

  componentWillUnmount() {
    if (navigator.platform.indexOf("Win") > -1) {
      ps.destroy();
    }
    window.removeEventListener("resize", this.resizeFunction);
  }

  componentDidUpdate(e) {
    if (e.history.location.pathname !== e.location.pathname) {
      this.refs.mainPanel.scrollTop = 0;
      if (this.state.mobileOpen) {
        this.setState({mobileOpen: false});
      }
    }
  }

  handleDrawerToggle = () => {
    this.setState({mobileOpen: !this.state.mobileOpen});
  };

  getRoute() {
    return this.props.location.pathname !== "/maps/full-screen-maps";
  }

  sidebarMinimize() {
    this.setState({miniActive: !this.state.miniActive});
  }

  resizeFunction() {
    if (window.innerWidth >= 960) {
      this.setState({mobileOpen: false});
    }
  }

  render() {
    const {classes, ...rest} = this.props;
    const mainPanel =
      classes.mainPanel +
      " " +
      cx({
        [classes.mainPanelSidebarMini]: this.state.miniActive,
        [classes.mainPanelWithPerfectScrollbar]:
        navigator.platform.indexOf("Win") > -1
      });
    return (
      <div className={classes.wrapper}>
        <Sidebar
          routes={dashboardRoutes}
          logoText={"ENO A3"}
          logo={logo}
          image={image}
          handleDrawerToggle={this.handleDrawerToggle}
          open={this.state.mobileOpen}
          color="blue"
          bgColor="black"
          miniActive={this.state.miniActive}
          {...rest}
        />
        <div className={mainPanel} ref="mainPanel">
          <Header
            sidebarMinimize={this.sidebarMinimize.bind(this)}
            miniActive={this.state.miniActive}
            routes={dashboardRoutes}
            handleDrawerToggle={this.handleDrawerToggle}
            {...rest}
          />
          {/* On the /maps/full-screen-maps route we want the map to be on full screen - this is not possible if the content and conatiner classes are present because they have some paddings which would make the map smaller */}
          {this.getRoute() ? (
            <div className={classes.content}>
              <div className={classes.container}>{switchRoutes}</div>
            </div>
          ) : (
            <div className={classes.map}>{switchRoutes}</div>
          )}
          {this.getRoute() ? <Footer fluid/> : null}
        </div>
      </div>
    );
  }
}

Dashboard.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withRouter(withStyles(appStyle)(Dashboard));

我有关于 ref 属性的弃用的抱怨。

所以我对这条线有抱怨

<div className={mainPanel} ref="mainPanel">

ps = new PerfectScrollbar(this.refs.mainPanel, {

我如何重写它以克服弃用?

更新

将 all 更改this.refs.mainPanel为后this.mainPanel,出现以下错误:

Uncaught TypeError: Cannot add property scrollTop, object is not extensible at Dashboard.componentDidUpdate (Dashboard.js:170)

这指的是原来的行

 this.refs.mainPanel.scrollTop = 0;

现在变成

this.mainPanel.scrollTop = 0;

标签: javascriptreactjseslint

解决方案


首先,您需要在构造函数中创建 ref(因为您使用的是构造函数):

constructor(props) {
  super(props);
  this.state = {
    mobileOpen: false,
    miniActive: false,
    logged_in: localStorage.getItem('token') ? true : false,
  };
  this.resizeFunction = this.resizeFunction.bind(this);
  this.mainPanel = React.createRef();
}

然后像这样使用它:

<div className={mainPanel} ref={this.mainPanel} >

相关文档。


推荐阅读