【发布时间】:2020-02-20 07:11:43
【问题描述】:
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;
}
class FancyButton extends React.Component {
focus() {
// ...
}
// ...
}
// Rather than exporting FancyButton, we export LogProps.
// It will render a FancyButton though.
export default logProps(FancyButton);
我从 react 文档中获取了这些代码,但是我对在此期间实际发生的事情感到困惑
export default logProps(FancyButton);
我的想法是它可能调用了函数 logProps,在 React 中它被认为是一个高阶组件,在这种情况下它应该使用大写字母以避免歧义。 logProp函数定义了一个类组件LogProps,类组件LogProps渲染了一个参数组件FancyButton。然后从函数返回类组件 LogProps。
import FancyButton from './FancyButton';
const ref = React.createRef();
// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}
/>;
从函数 logProps 中返回的组件(LogProps,FancyButton)然后被导入并在
处实例化<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}
/>
这是正确的吗?
【问题讨论】:
标签: reactjs