我正在将我的应用程序移至Material UI V4的过程中,并且在以编程方式设置“ to”道具时,我正在努力将我的React Router Link组件移至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>
答案 0 :(得分:1)
类似以下的方法应该可以正常工作。 ViewLink
可以在单独的文件中定义,如果要重用,可以导入。您可以通过在Button元素上指定属性来传递需要传递给ViewLink
的任何属性。这样,component
道具就可以指向可重用的类型,而不是内联函数。
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>