当扩展一个类时,我可以轻松地向它添加一些新属性。
但是,如果当我扩展基类时,我想向基类的对象(简单对象的属性)添加新属性怎么办?
这是一个带有一些代码的示例。
基类
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) 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) class ×1
css ×1
extends ×1
inheritance ×1
material-ui ×1
object ×1
reactjs ×1
sx ×1
typescript ×1