【问题标题】:React: class to function component where class extends and has constructor with parametersReact:类到函数组件,其中类扩展并具有带参数的构造函数
【发布时间】:2021-12-13 15:23:02
【问题描述】:

当一个类组件从另一个类扩展时如何重写?构造函数中的参数让我不确定如何处理。有人有想法吗?

代码示例。

class Animal extends React.Component {
    constructor(name, action, addKeywords = [], addHashtag = []) {
        super();
        this.name = name;
        this.action= action;
        this.currentUser = new CurrentUser();
        this.keywordList = FILTER_BY_KEYWORDS.concat(addKeywords );
        this.hashtagList = addHashtag;
    }

    nameChange(name) { ... }
}

class Lion extends Animal {
    render() {
        return <Item name={this.nameChange} />
    }
}

【问题讨论】:

  • Animal 不是 React 组件。它不返回任何 JSX。

标签: javascript reactjs class functional-programming


【解决方案1】:

虽然在类组件中从不鼓励继承,但有时我们无法选择要迁移到 Hooks 的遗留代码的形状。每个旧组件都会有所不同,我不鼓励任何人在使用 React Hooks 开发新项目时编写以下代码。

也就是说,以下是将特定类结构从问题中最“直接地翻译”为我能想到的带有钩子的函数组件:

function useAnimal(name, action, addKeywords = [], hashtagList = []) {
  const self = React.useRef()
  if (!self.current) {
    // simulate synchronous constructor method, using the initial prop values
    self.current = {
      name,
      action,
      currentUser: new CurrentUser(),
      keywordList: FILTER_BY_KEYWORDS.concat(addKeywords),
      hashtagList,
      nameChange: (name) => { ... } 
    }
  }

  return self.current
}


function Lion({name, action, addKeywords, addHashtag}) {
  const {nameChange} = useAnimal(name, action, addKeywords, addHashtag)

  return <Item name={nameChange} />
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2013-11-15
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多