子组件重新渲染过多

我建立一个标签组件

https://medium.com/@diegocasmo/a-simple-react-tabs-component-47cac2cfbb5

但是,当我单击“选项卡”时,会导致重新渲染过多。这是我的代码:

Tabs.tsx

const Tabs: React.FC<Props> = ({defaultTabIndex, children}) => {
    const [activeTabIndex, setActiveTab] = useState<Number>(defaultTabIndex);

    const handleTabClick = useCallback((tabIndex) => {
        setActiveTab(tabIndex);
    }, []);

    const renderChildrenTab = useMemo(() => {
        return React.Children.map(children, (child, index) => {
            return React.cloneElement(child as ReactElement, {
                onClick: handleTabClick,
                tabIndex: index,
                isActive: index === activeTabIndex
            });
        })
    }, [activeTabIndex]);

    const renderActiveTabContent = () => {
        if (children) {
            // @ts-ignore
            return Array.isArray(children) ? children[activeTabIndex].props.children : children.props.children
        }
    };

    return (
        <React.Fragment>
            <div className="flex flex-row bg-gray-200 border-gray-400 border-b h-16 items-center text-gray-600 pl-5">
                {renderChildrenTab}
            </div>
            <div className="p-6">
                <div className="border border-gray-400 h-40">
                    {renderActiveTabContent()}
                </div>
            </div>
        </React.Fragment>
    )
};

Tab.tsx //此组件重新渲染过多

const Tab: React.FC<Props> = ({onClick, tabIndex, isActive, iconClassName, toolTipText}) => {
    console.log('render tab');
    return (
        <React.Fragment>
            <button className={classNames("focus:outline-none hover:bg-gray-300 h-10 w-10 tooltip",
                {
                    "bg-gray-400": isActive,
                })}
                    onClick={(event) => {
                        event.preventDefault();
                        if (onClick && tabIndex !== undefined) onClick(tabIndex);
                    }}>
                <i className={iconClassName}/>
                <span className="tooltiptext text-xs font-thin">{toolTipText}</span>
            </button>

        </React.Fragment>
    )
};

使用

                    <Tabs defaultTabIndex={3}>
                        <Tab
                            iconClassName={'far fa-image'}
                            toolTipText={'Image'}
                        >
                           ...
                            <div/>
                        </Tab>
</Tabs>

我哪里错了?请帮我

评论