[英]Converting a class into const stateless function
Hello below I have a class that doesn't use any life-cycle methods or states, I have read documentation about converting such classes into consts. 您好,下面我有一个不使用任何生命周期方法或状态的类,我已阅读有关将此类转换为const的文档。 however, I'm not sure how I seem to struggle with the below class:
但是,我不确定我如何在以下课程中挣扎:
class ContractsTableHead extends Component {
createSortHandler(property) {
return event => {
this.props.onRequestSort(event, property);
};
}
render() {
const { order, orderBy } = this.props;
return (
<TableHead>
<TableRow>
{rows.map(
row => (
<TableCell
key={row.id}
align={row.numeric ? "right" : "left"}
padding={row.disablePadding ? "none" : "default"}
sortDirection={orderBy === row.id ? order : false}
>
<Tooltip
title="Sort"
placement={row.numeric ? "bottom-end" : "bottom-start"}
enterDelay={300}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={this.createSortHandler(row.id)}
>
{row.label}
</TableSortLabel>
</Tooltip>
</TableCell>
),
this
)}
</TableRow>
</TableHead>
);
}
}
ContractsTableHead.propTypes = {
onRequestSort: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
rowCount: PropTypes.number.isRequired
};
export default ContractsTableHead;
If you make the class component into a function component, you need to make your method createSortHandler
into a regular function as well: 如果将类组件变成函数组件,则还需要将方法
createSortHandler
变成常规函数:
const ContractsTableHead = props => {
const createSortHandler = property => {
return event => {
props.onRequestSort(event, property);
};
};
const { order, orderBy } = props;
return (
<TableHead>
<TableRow>
{rows.map(row => (
<TableCell
key={row.id}
align={row.numeric ? "right" : "left"}
padding={row.disablePadding ? "none" : "default"}
sortDirection={orderBy === row.id ? order : false}
>
<Tooltip
title="Sort"
placement={row.numeric ? "bottom-end" : "bottom-start"}
enterDelay={300}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={createSortHandler(row.id)}
>
{row.label}
</TableSortLabel>
</Tooltip>
</TableCell>
))}
</TableRow>
</TableHead>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.