【发布时间】:2021-05-10 19:53:38
【问题描述】:
我将 Next.js (10.2) 和 Material-UI (MUI) 与 Typescript 一起使用,并拥有一个自定义的 Link 组件:
Link.tsx (/components)
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withRouter } from 'next/router';
import NextLink from 'next/link';
import MuiLink from '@material-ui/core/Link';
function NextComposed(props) {
const { as, href, prefetch, forwardedRef, ...other } = props;
return (
<NextLink href={href} prefetch={prefetch} as={as}>
<a {...other} ref={forwardedRef} />
</NextLink>
);
}
NextComposed.propTypes = {
as: PropTypes.string,
href: PropTypes.string.isRequired,
prefetch: PropTypes.bool,
forwardedRef: PropTypes.any.isRequired,
children: PropTypes.node.isRequired,
}
const NextComposedWithRef = React.forwardRef((props, ref) => <NextComposed {...props} forwardedRef={ref} />)
// A styled version of the Next.js Link component:
// https://nextjs.org/docs/#with-link
function Link(props) {
const { activeClassName, router, className: classNameProps, naked, ...other } = props;
const className = clsx(classNameProps, {
[activeClassName]: router.pathname === props.href && activeClassName,
});
if (naked) {
return <NextComposed className={className} {...other} />;
}
return <MuiLink component={NextComposedWithRef} className={className} {...other} />
}
Link.propTypes = {
activeClassName: PropTypes.string,
as: PropTypes.string,
className: PropTypes.string,
href: PropTypes.string,
naked: PropTypes.bool,
onClick: PropTypes.func,
prefetch: PropTypes.bool,
router: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
children: PropTypes.node.isRequired,
};
Link.defaultProps = {
activeClassName: 'active',
};
export default withRouter(Link)
我也有它的另一个版本,它工作正常。但问题不在于Link 本身,而是当我尝试创建另一个包含我的Link 的component 时,出现以下错误:
CharacterButtons.tsx
type characterButtons {
name: string
}
const CharacterButtons: FC<characterButtons> = ({ name }) => {
const classes = useStyles();
return (
<Fragment>
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
>
<Link href={`https://www.example.com/character/${name}`} prefetch={false}>
<Avatar variant="square" src={`./test.png`} className={classes.large}/>
</Link>
</Grid>
</Fragment>
)
};
export default CharacterButtons;
据我了解,它以某种方式与 HTMLPropertyIntrinsicAttributes 类型及其扩展名有关,但我不知道如何。另外,我找到了一些打字方法来避免以下错误,但结果,我需要将父 FC 的每个参数转移到我的 Link,例如:
<Link href={`https://www.example.com/character/${name}`} prefetch={false} ...{parent-props}>
【问题讨论】:
标签: javascript reactjs typescript next.js