问题描述:通过externals 或是 动态连接库 加载react,ref 会直接被透传
// App.js
import React, { forwardRef, useRef } from "react";
function logProps(WrappedComponent) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log("old props:", prevProps);
console.log("new props:", this.props);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return LogProps;
}
// 注意:这里是函数组件
function FancyButton(props, ref) {
console.log(ref);
return <div ref={ref}>sssss</div>;
}
const MFancyButton = forwardRef((props) => {
const MemodFancyButton = logProps(FancyButton);
return <MemodFancyButton {...props} />;
});
export default function App() {
const dsRef = useRef();
return <MFancyButton ref={dsRef} />;
}
- 上述代码在项目针对
react
和react-dom
配置了externals
或dll
之后,不会报错
// webpack.config.js
externals: {
"react": "React",
"react-dom": "ReactDOM",
},
// index.html
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
- 如果未设置
externals
或dll
,则会报如下错误