当React 16中不赞成`this.refs`时,如何使用`mainPanel`?

时间:2018-09-21 00:16:01

标签: javascript reactjs eslint

我有一个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, {

我该如何重写以克服过时的要求?

更新

将所有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;

2 个答案:

答案 0 :(得分:1)

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

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} >

Related documentation.

答案 1 :(得分:0)

更新React 16之后,我遇到了同样的问题。实际上,解决起来很简单: 来自React Docs

  

将ref传递给render中的元素时,将引用该节点   在引用的当前属性中可以访问。

因此,在构造函数中创建ref并将其附加到元素之后,访问ref所需要做的就是使用this.mainPanel.current.scrollTop

这将有助于避免出现“不可扩展对象”错误。