您好,下面我有一个不使用任何生命周期方法或状态的类,我已阅读有关将此类转换为const的文档。但是,我不确定我在下面的课程中看起来如何挣扎:
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;
答案 0 :(得分:3)
如果将类组件变成函数组件,则还需要将方法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>
);
};