Can this forwardRef be moved into a function for reusability?

假如想象 提交于 2019-12-11 12:54:47

问题


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.

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>

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>

回答1:


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>


来源:https://stackoverflow.com/questions/56383088/can-this-forwardref-be-moved-into-a-function-for-reusability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!