我一直在努力将此功能组件转换为类。 我使用了npm-breadcrumbs-hoc插件。它完美地工作只需要 将其转换为以下格式:
类面包屑扩展了React.Component { ... }
有人可以向我解释如何做吗? 下面是我的代码:
import React from 'react';
import { NavLink } from 'react-router-dom';
import WithBreadcrumbs from 'react-router-breadcrumbs-hoc';
import './Breadcrumb.css';
const merchantBreadcrumb = ({ match }) =>
<span>{match.params.merchantName}</span>;
const routes = [
{ path: '/merchant/:merchantName', breadcrumb: merchantBreadcrumb },
];
const breadcrumb = ({ breadcrumbs }) => (
<div className="breadcrumbComponent">
{breadcrumbs.map((breadcrumb, index) => (
<span key={breadcrumb.key}>
<NavLink
className = 'highlight'
to = {breadcrumb.props.match.url}
>
{breadcrumb}
</NavLink>
{(index < breadcrumbs.length - 1) && <i> > </i>}
</span>
))}
</div>
);
export default WithBreadcrumbs(routes)(breadcrumb);
答案 0 :(得分:0)
您可以通过以下方式进行操作:
/* your imports and other declarations stays the same*/
class Breadcrumb extends React.Component {
render(){
return (<div className="breadcrumbComponent">
{this.props.breadcrumbs.map((breadcrumb, index) => (
<span key={breadcrumb.key}>
<NavLink
className = 'highlight'
to = {breadcrumb.props.match.url}
>
{breadcrumb}
</NavLink>
{(index < breadcrumbs.length - 1) && <i> > </i>}
</span>
))}
</div>
)
}
export default WithBreadcrumbs(routes)(BreadCrumb);
答案 1 :(得分:0)
您的({breadCrumbs})
是props
的原始结构。
您的breadCrumbs
是匿名函数的处理程序,该函数返回包裹在<div className="breadcrumbComponent">
中的组件。
因此,您需要在render()
函数中返回它。
class BreadCrumb extends React.Component {
render() {
const {breadcrumbs} = this.props;
return (
<div className="breadcrumbComponent">
{breadcrumbs.map((breadcrumb, index) => (
<span key={breadcrumb.key}>
<NavLink
className = 'highlight'
to = {breadcrumb.props.match.url}
>
{breadcrumb}
</NavLink>
{(index < breadcrumbs.length - 1) && <i> > </i>}
</span>
))}
</div>
);
}
}
老实说,由于您没有使用任何状态,因此我看不到这种好处。
如果您需要React生命周期方法(例如compoenentDidMount
,componentWillUnmount
等)或需要保持其自身状态,则类组件很有用。
答案 2 :(得分:0)
您也许可以尝试一下(未经测试)
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import WithBreadcrumbs from 'react-router-breadcrumbs-hoc';
import './Breadcrumb.css';
const merchantBreadcrumb = ({ match }) => <span>{match.params.merchantName}</span>;
const routes = [
{ path: '/merchant/:merchantName', breadcrumb: merchantBreadcrumb }
]
export class WithBreadcrumbs extends Component {
static propTypes = {
breadcrumbs: PropTypes.array.isRequired
}
render() {
const { breadcrumbs } = this.props;
return (
<div className="breadcrumbComponent">
{
breadcrumbs.map((breadcrumb, index) => (
<span key={breadcrumb.key}>
<NavLink
className='highlight'
to={breadcrumb.props.match.url}
>
{breadcrumb}
</NavLink>
{(index < breadcrumbs.length - 1) && <i> > </i>}
</span>
))
}
</div>
);
}
};
export default routes(WithBreadcrumbs);