reactjs - 在反应中将类组件转换为功能组件
问题描述
我有一个看起来像这样的类组件。
class CommentSummary extends React.Component<Properties> {
constructor(props: Properties) {
super(props)
this.onOpen = this.onOpen.bind(this)
}
onOpen() {
const {
props: {
question,
newestChild: { id },
onOpen,
},
} = this
if (!question) {
return
}
onOpen(question.id, id)
}
}
我希望能够将其转换为如下代码所示的功能组件。我在下面的 onOpen 方法中得到了曲折的线条。如何转换下面的 onOpen 方法?
const CommentSummary = (props: Properties) => {
onOpen() {
const {
props: {
question,
newestChild: { id },
onOpen,
},
} = this
if (!question) {
return
}
onOpen(question.id, id)
}
}
export default CommentSummary
解决方案
因为函数组件确实有这个(初始化引用实例)。因此,您应该将函数声明为 const :
const CommentSummary = (props: Properties) => {
const onOpen = () => {
const {
question,
newestChild: { id },
onOpen,
} = props;
if (!question) {
return
}
onOpen(question.id, id)
}
}
推荐阅读
- java - 有关“代码蝙蝠”问题的算法问题
- python - 使用两个 np.linspace,如何用复数填充二维数组?
- java - 列表的值不会以编程方式更改
- python - ValueError:形状不匹配
- elixir - 如何在 where 子句的 Ecto 查询中使用变量
- javascript - Angularjs:尝试从 json 创建动态下拉列表
- hugo - 如何防止默认的学术主题覆盖我的 Hugo 网站上的黑暗主题?
- php - 为什么不接受 laravel 的验证
- javascript - “node_modules”中的几个包丢失了。如何?为什么?在哪里?
- java - 突出显示树表视图或树视图中的特定项目