React 18 中对于children的处理

1,049 阅读1分钟

升级了react18之后,react官方移除了对于默认children的支持,所以但保留了PropsWithChildren,如果需要使用children的话就使用PropsWithChildren

定义组件:

import React, { PropsWithChildren } from 'react'
import { Tooltip } from 'antd'

declare type RenderFunction = () => React.ReactNode;

interface Props {
    title : React.ReactNode | RenderFunction;
}

// 有了PropsWithChildren之后,我们就可以使用children了:
const e: React.FC<PropsWithChildren<Props>> = ({title, children}) => {
    return (
        <Tooltip 
            title={title} 
            key={new Date().getTime().toString()}
            overlayInnerStyle={{ borderRadius: 6 }}>
            {children ? children : null}
        </Tooltip>
    )
} 

export default e

使用组件:

<Tooltip title="prompt text">
    <span className="inline-block i_icon_24 i_info_circle m_l_4" />
</Tooltip>