Antd 导出 button 组件时用了 forwardRef
来源:4-11 精益求精 - Buton 组件编码第二部分

liio6
2022-11-26
老师你好,
1. forwardRef
Antd 源码第 319 行 (https://github.com/ant-design/ant-design/blob/master/components/button/button.tsx):
最后导出 Button 组件时,为什么用到
const Button = React.forwardRef<unknown, ButtonProps>(InternalButton) as CompoundedComponent
而不是直接 export default InternalButton 呢
2. iconNode
const iconNode =
icon && !innerLoading ? (
icon
) : (
<LoadingIcon existIcon={!!icon} prefixCls={prefixCls} loading={!!innerLoading} />
);
<button
{...(rest as NativeButtonProps)}
type={htmlType}
className={classes}
onClick={handleClick}
disabled={mergedDisabled}
ref={buttonRef}
>
{iconNode}
{kids}
</button>
这里为什么没有像下面这样。在JSX里直接写,而是要用 iconNode 包起来呢?
<button
{...(rest as NativeButtonProps)}
type={htmlType}
className={classes}
onClick={handleClick}
disabled={mergedDisabled}
ref={buttonRef}
>
{
icon && !innerLoading
? (icon)
: (<LoadingIcon existIcon={!!icon} prefixCls={prefixCls} loading={!!innerLoading} />);
}
{kids}
</button>
写回答
1回答
-
同学你好
1 forwardRef 是为了在父组件引用的时候暴露出真正的 DOM 节点,如果你注意看我们的后面的内容和源码(比如 Input 组件),其实最终也用了 forwardRef,为了给包裹 Input 组件的父组件使用。
2 我认为这样写没有什么特殊的,只是降这段逻辑抽象给一个变量,这样用起来应该更清晰吧。
012022-11-29
相似问题