可以将此forwardRef移入函数以实现可重用性吗? [英] Can this forwardRef be moved into a function for reusability?

查看:67
本文介绍了可以将此forwardRef移入函数以实现可重用性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的应用程序移至Material UI V4的过程中,并且在以编程方式设置"to"道具时,我正在努力将我的React Router Link组件移至forwardRef包装的组件中.

I am in the process of moving my application to Material UI V4 and I am struggling to move my react router Link components into forwardRef wrapped components when the 'to' prop is set programmatically.

下面的代码可以工作,但是需要复制对forwardRef的调用并构建props对象,我更愿意在一次使用参数调用函数的情况下进行该工作,但我无法解决该问题.

The below code works but requires duplicating the call to forwardRef and building the props object and I would prefer to do that work in a function that is called once with arguments but I cannot work out how to do it.

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的函数?理想情况下,如下所示:

Is there a way to create a single function that handles both the switch statement and the forwardRef? Ideally, something called as per below:

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

推荐答案

类似以下的方法应该可以正常工作.可以在单独的文件中定义ViewLink并导入(如果要重复使用的话).您可以通过在Button元素上指定要传递给ViewLink的任何属性来传递它们.这样,component道具就可以指向可重用的类型,而不是内联函数.

Something like the following should work fine. ViewLink can be defined in a separate file and imported if you want to reuse it. Any properties that you need to pass to ViewLink can be passed by specifying them on the Button element. That allows the component prop to point at a reusable type rather than an inline function.

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>

这篇关于可以将此forwardRef移入函数以实现可重用性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆