这个 forwardRef 可以移动到一个函数中以实现可重用性吗?

IT技术 javascript reactjs material-ui
2021-05-02 01:34:49

我正在将我的应用程序移动到 Material UI V4,当以编程方式设置“to”props时,我正在努力将我的react-router链接组件移动到 forwardRef 包装的组件中。

下面的代码有效,但需要复制对 forwardRef 的调用并构建 props 对象,我更愿意在一个用参数调用一次的函数中完成这项工作,但我不知道如何去做。

const ViewLink = (props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
}

<Button 
    className={classes.buttonFont}
    component={React.forwardRef((props, ref) => ViewLink(
        { 
            id: childData.id, 
            type: type, 
            ...props
        }, 
            ref
    ))}
>
    {childData[column]}
</Button>

有没有办法创建一个处理 switch 语句和 forwardRef 的函数?理想情况下,如下所示:

<Button 
    className={classes.buttonFont}
    component={(props) => ViewLink(id, type, props)}
>
    {childData[column]}
</Button>
1个回答

像下面这样的东西应该可以正常工作。ViewLink可以在单独的文件中定义并导入,如果您想重用它。您需要传递的任何属性ViewLink都可以通过在 Button 元素上指定它们来传递。这允许componentprop 指向可重用类型而不是内联函数。

const ViewLink = React.forwardRef((props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
});
<Button 
    className={classes.buttonFont}
    id={childData.id}
    component={ViewLink}
>
    {childData[column]}
</Button>