javascript - 当React 16中不推荐使用 `mainPanel`时,如何使用 `this.refs`?

标签 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 属性的弃用有 eslint 投诉。

所以我对这条线有提示

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

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

如何重写它以克服弃用?

更新

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

未捕获的类型错误:无法添加属性scrollTop,对象不可扩展 在 Dashboard.componentDidUpdate (Dashboard.js:170)

这是指原来的行

 this.refs.mainPanel.scrollTop = 0;

现在变成了

this.mainPanel.scrollTop = 0;

最佳答案

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

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.

关于javascript - 当React 16中不推荐使用 `mainPanel`时,如何使用 `this.refs`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52434920/

相关文章:

reactjs - eslint-plugin-react 找不到规则

javascript - php/mysql 时间数据检索并创建倒计时

javascript - 放大时工具提示文本超出工具提示

react-router - 使用 React Router 进行转换/重定向的真正正确方法是什么?

reactjs - 如何用接口(interface)满足 Record<string, unknown> 的约束

angular - 在 Visual Studio Code 中运行的 Angular 应用程序中,TSLint 扩展抛出错误

javascript - jQuery : Page is reloading after clicking remove button of that div

javascript - 包含空字符串的 HTML 属性不显示 = 运算符

reactjs - @react-pdf/渲染器。如何生成PDF并下载

reactjs - 在 React 应用程序中测试 Select 元素