小编Clo*_*lla的帖子

Typescript 继承:扩展基类对象属性

当扩展一个类时,我可以轻松地向它添加一些新属性。

但是,如果当我扩展基类时,我想向基类的对象(简单对象的属性)添加新属性怎么办?

这是一个带有一些代码的示例。

基类

type HumanOptions = {
  alive: boolean
  age: number
}

class Human {
  id: string
  options: HumanOptions

  constructor() {
    this.id = '_' + Math.random()

    this.options = {
      alive: true,
      age: 25,
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

派生类

type WizardOptions = {
  hat: string
} & HumanOptions

class Wizard extends Human{
 
  manaLevel: number
  options: WizardOptions // ! Property 'options' has no initializer and is not definitely assigned in the constructor.

  constructor() {
    super()
    this.manaLevel = 100
    this.options.hat = "pointy" // …
Run Code Online (Sandbox Code Playgroud)

inheritance extends class object typescript

24
推荐指数
2
解决办法
6561
查看次数

MUI - 扩展 sx props 以记住值并避免重新渲染

MUIsx的 prop对于速度和代码可读性很有用(合理),但它可能会导致许多不必要的重新渲染(这会导致性能下降)。sx

所以我想知道是否有办法添加 useMemo 包装版本的 MUIsx道具。我将如何扩展 MUI 来实现这一目标?

这是我的意思的一个简化示例。

基地情况:

const MyComponent = () => {

  return
    <>
      <Box sx={{color: "red"}}> I am a bit static </Box>
      <Box sx={{width: window.innerWidth + "px"}}> I am so dynamic! </Box>
    </>  
};
Run Code Online (Sandbox Code Playgroud)

这将是(在本例中是过度的)优化:

const MyComponent = () => {
  const boxStyle = useMemo(() => ({color: "red"}), [])

  return
    <>
      <Box sx={boxStyle}> I am a bit static </Box>
      <Box sx={{width: window.innerWidth + "px"}}> I am so dynamic! …
Run Code Online (Sandbox Code Playgroud)

css reactjs material-ui react-usememo sx

5
推荐指数
0
解决办法
911
查看次数