gpt4 book ai didi

reactjs - 如何扩展 React 组件?

转载 作者:行者123 更新时间:2023-12-03 13:00:52 29 4
gpt4 key购买 nike

假设有一个我喜欢的 React 组件,但想要修改。对于此示例,我们将使用 Material UI 的 LinearProgress。我想用它制作一个可点击的搜索栏。

class SeekBar extends LinearProgress {
componentDidMount() {
super.componentDidMount();
console.log('my stuff here');
}
}

但我觉得就改变 render 返回的内容而言,我能做的可能非常有限。不过,也许我对这一切的看法都是错误的。如果我喜欢某个特定的 React 组件(例如 Material UI 组件),那么有什么好的、可重用的方法来自定义其外观和功能并使其成为我自己的组件?

最佳答案

在 ES6/JSX/React 世界中,您可以通过多种方式扩展组件行为和值。考虑到您使用 Material UI,我建议您使用以下其中一项。

第一种情况:

您有两个从 React 扩展 Component 的组件:

class ExampleComponent extends React.Component {
render () {
return(
<div>
<button {...this.props}>
Click me!
</button>
</div>
)
}
}

class RenderComponent extends React.Component {
clickHandler () {
console.log('Click fired!')
}

render () {
return(
<ExampleComponent onClick={this.clickHandler.bind(this)} />
)
}
}

在该示例中,onClick 通过渲染的 ExampleComponent 内的 props 传递。 Example here .

第二种情况:

这与 Material UI 如何扩展自己的组件类似:

class ExampleComponent extends React.Component {
clickHandler () {
console.log('Click fired!')
}
}

class RenderComponent extends ExampleComponent {
render () {
return(
<div>
<button onClick={this.clickHandler.bind(this)}>
Click me!
</button>
</div>
)
}
}

在此示例中,您有一个从 React 扩展 Component 的组件,但仅具有事件方法。然后,您扩展此组件并使用扩展的行为呈现您自己的组件。 Here is a live example .

希望对你有帮助!

关于reactjs - 如何扩展 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677235/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com