首页 > 解决方案 > 在反应中将类组件转换为功能组件

问题描述

我有一个看起来像这样的类组件。

    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

标签: reactjs

解决方案


因为函数组件确实有这个(初始化引用实例)。因此,您应该将函数声明为 const :

const CommentSummary = (props: Properties) => {

    const onOpen = () => {
        const {
            question,
            newestChild: { id },
            onOpen,
        } = props;
        if (!question) {
            return
        }

        onOpen(question.id, id)
    }
}

推荐阅读