为了将引用传递给由withRouter 包裹的组件,您需要将其命名为wrappedComponentRef。我建议将 withRouter 作为最外层的包装器,因此您的示例如下所示:
withRouter(connect(null, null, null, {forwardRef: true})(myCom));
<myCom wrappedComponentRef={ref => this.myCom = ref} />
以下示例和描述改编自我的相关答案:Get ref from connected redux component withStyles
下面是react-redux todo list tutorial 的修改版本的代码,它显示了正确的语法。我在此处包含了我更改的两个文件(TodoList.js 和 TodoApp.js),但沙盒是一个完整的示例。
在TodoApp 中,我使用TodoList 上的引用(通过wrappedComponentRef 属性)来获取并显示其高度。仅当TodoApp 重新渲染时,显示的高度才会更新,因此我包含了一个按钮来触发重新渲染。如果你在 todo 列表中添加了几个 todo,然后点击重新渲染按钮,你会看到列表的新高度显示出来(表明 ref 已经完全工作了)。
在TodoList 中,我使用withStyles 在待办事项列表周围添加蓝色边框以显示withStyles 正在工作,并且我正在显示主题中的原色以显示withTheme工作中。我还展示了来自withRouter 的location 对象,以证明withRouter 正在工作。
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";
import { withRouter } from "react-router-dom";
const styles = {
list: {
border: "1px solid blue"
}
};
const TodoList = React.forwardRef(
({ todos, theme, classes, location }, ref) => (
<>
<div>Location (from withRouter): {JSON.stringify(location)}</div>
<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 withRouter(
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 wrappedComponentRef={todoListRef} />
<VisibilityFilters />
<button onClick={incrementRenderIndex}>
Trigger re-render of TodoApp
</button>
<div>Render Index: {renderIndex}</div>
</div>
);
}