从连接的 redux 组件获取 ref withStyles

IT技术 reactjs react-redux material-ui
2021-05-14 22:17:31

我有一个工作组件的导出:

export default connect(
    mapStateToProps, actions,
    null, { withRef: true, forwardRef: true }
  )(withTheme()(withStyles(styles)(MainMenu)));

它的电话:

<MainMenu 
  ref={(connectedMenu) => this.menuRef = connectedMenu.getWrappedInstance()} 
  user={user} 
/>

我希望得到一个 MainMenu ref,但我一直在得到 WithTheme 对象。

我也尝试通过innerRef,但出现以下错误:

TypeError: connectedMenu.getWrappedInstance is not a function
TypeError: Cannot read property 'getWrappedInstance' of null

在这一切之前,我已经尝试过这种React.createRef()格式,但没有奏效。

我如何获得这个参考?

1个回答

假设您使用的是 Material-UI 的 v4,则您的语法withTheme不正确。在 v4 中删除了第一组括号

代替

withTheme()(YourComponent)

你应该有

withTheme(YourComponent)

下面是来自react-redux 待办事项列表教程的修改版本的代码,显示了正确的语法。我在此处包含了我更改的两个文件(TodoList.js 和 TodoApp.js),但沙箱是一个完整的示例。

在 中TodoApp,我使用 refTodoList来获取并显示其高度。显示的高度只会在TodoApp重新渲染时更新,所以我添加了一个按钮来触发重新渲染。如果在待办事项列表中添加几个待办事项,然后单击重新渲染按钮,您将看到列表的新高度显示出来(表明 ref 已完全工作)。

在 中TodoList,我使用withStyles在待办事项列表周围添加蓝色边框来显示它withStyles正在工作,并且我正在显示主题的主要颜色以表明它withTheme正在工作。

TodoList.js

import React from "react";
import { connect } from "react-redux";
import Todo from "./Todo";
import { getTodosByVisibilityFilter } from "../redux/selectors";
import { withStyles, withTheme } from "@material-ui/core/styles";
import clsx from "clsx";

const styles = {
  list: {
    border: "1px solid blue"
  }
};
const TodoList = React.forwardRef(({ todos, theme, classes }, ref) => (
  <>
    <div>theme.palette.primary.main: {theme.palette.primary.main}</div>
    <ul ref={ref} className={clsx("todo-list", classes.list)}>
      {todos && todos.length
        ? todos.map((todo, index) => {
            return <Todo key={`todo-${todo.id}`} todo={todo} />;
          })
        : "No todos, yay!"}
    </ul>
  </>
));

const mapStateToProps = state => {
  const { visibilityFilter } = state;
  const todos = getTodosByVisibilityFilter(state, visibilityFilter);
  return { todos };
};
export default connect(
  mapStateToProps,
  null,
  null,
  { forwardRef: true }
)(withTheme(withStyles(styles)(TodoList)));

TodoApp.js

import React from "react";
import AddTodo from "./components/AddTodo";
import TodoList from "./components/TodoList";
import VisibilityFilters from "./components/VisibilityFilters";
import "./styles.css";

export default function TodoApp() {
  const [renderIndex, incrementRenderIndex] = React.useReducer(
    prevRenderIndex => prevRenderIndex + 1,
    0
  );
  const todoListRef = React.useRef();
  const heightDisplayRef = React.useRef();
  React.useEffect(() => {
    if (todoListRef.current && heightDisplayRef.current) {
      heightDisplayRef.current.innerHTML = ` (height: ${
        todoListRef.current.offsetHeight
      })`;
    }
  });
  return (
    <div className="todo-app">
      <h1>
        Todo List
        <span ref={heightDisplayRef} />
      </h1>
      <AddTodo />
      <TodoList ref={todoListRef} />
      <VisibilityFilters />
      <button onClick={incrementRenderIndex}>
        Trigger re-render of TodoApp
      </button>
      <div>Render Index: {renderIndex}</div>
    </div>
  );
}

使用 Redux 编辑 Todo 应用