javascript - 在反应中将多个返回从类组件转换为功能组件
问题描述
我正在尝试将基于反应本机的类转换为基于函数的类,并且我遇到了一个具有 2 个返回语句的类组件,我不知道如何将其转换为函数组件。这是类组件。请注意,我省略了不重要的代码
export default class Card extends Component {
static defaultProps = {
shadow: true,
border: true,
title: null,
}
renderHeader = () => {
const { title } = this.props;
if (!title) return null;
return (
<Block row space="between" style={styles.header}>
<Text caption>{title}</Text>
<TouchableOpacity>
{/* <Icon options /> */}
</TouchableOpacity>
</Block>
)
}
render() {
const { shadow, border, style, children, ...props } = this.props;
const cardStyles = [
styles.card,
shadow && styles.shadow,
border && styles.border,
style,
];
return (
<Block style={cardStyles} {...props}>
{this.renderHeader()}
{children}
</Block>
)
}
}
这就是我想出的
const Card = title => {
static defaultProps = {
shadow: true,
border: true,
title: null,
}
renderHeader = () => {
const { title } = title;
if (!title) return null;
}
renderHeader = () => {
const { title } = this.props;
if (!title) return null;
}
const { shadow, border, style, children, ...props } = this.props;
const cardStyles = [
styles.card,
shadow && styles.shadow,
border && styles.border,
style,
];
return [
<Block row space="between" style={styles.header}>
<Text caption>{title}</Text>
<TouchableOpacity>
{/* <Icon options /> */}
</TouchableOpacity>
</Block> <
Block style = { cardStyles } { ...props } > { renderHeader() } { children } <
/Block>
]
}
请注意,当我运行代码时,它没有显示任何错误,还请注意,在问这个问题之前,我已经浏览了这里和搜索引擎,但没有找到任何合适的答案
解决方案
所有功能组件都有一个参数 prop object 。所以我们可以解构并分配默认值。所以你的代码
static defaultProps = {
shadow: true,
border: true,
title: null,
}
现在改为
const Card = ({
shadow = true,
border = true,
title = null,
style,
children,
...props
}) => {
类组件中的方法变为功能组件中的函数。所以你可以改变你renderHeader
的
const renderHeader = () => {
....
};
由于您的 renderHeader 只是另一个函数,因此您可以this
在调用它时删除
{renderHeader()}
转换组件
const Card = ({
shadow = true,
border = true,
title = null,
style,
children,
...props
}) => {
const renderHeader = () => {
if (!title) return null;
return (
<Block row space="between" style={styles.header}>
<Text caption>{title}</Text>
<TouchableOpacity>{/* <Icon options /> */}</TouchableOpacity>
</Block>
);
};
const cardStyles = [
styles.card,
shadow && styles.shadow,
border && styles.border,
style,
];
return (
<Block style={cardStyles} {...props}>
{renderHeader()}
{children}
</Block>
);
};
export default Card;
参考
推荐阅读
- react-native - React Native 不会重新运行 componentDidMount
- javascript - 如何使用 react-big-calendar 的 onSelectSlot 方法在多天创建事件?
- ajax - 从 bean(primefaces)控制 onClick 或 onSucess 事件?
- ms-access - 我从拆分表中删除了一个字段,现在我在前端看不到连续表单
- python - 如何在不迭代查询集的情况下将 Django QuerySet 转换为包含对象列表的字典?
- python - 在 PyPDF PdfFileReader 中循环浏览页面范围会产生奇怪的循环
- php - 在 PHP 7.4 异常的源代码中包含 __wakeup 有什么意义?
- javascript - 在反应应用程序中更改数组中日期字段的格式
- reactjs - Material-UI 4.1.2 样式选择 SelectInput
- amazon-web-services - 如何与外部用户共享公共 S3 存储桶?