reactjs - 扩展组件时如何初始化状态?
问题描述
我有一个名为的组件ErrorComponent
,其状态在其构造函数中初始化。
但是,我现在想创建一个名为的新类BaseForm
,它从ErrorComponent
.
但如果我这样做
export default class BaseForm extends ErrorComponent {
constructor(props) {
super(props);
this.setState({
reason: null
});
它对我大喊大叫,说我不应该setState
在构造函数中使用。
如果我这样做
export default class BaseForm extends ErrorComponent {
constructor(props) {
super(props);
this.state = {
reason: null
};
它似乎正在覆盖ErrorComponent
构造函数的状态。如何在不覆盖我要扩展的类的状态的情况下设置状态?
解决方案
你不应该在 React 中使用继承,除非通过组合无法实现所需的功能。这是React
反模式。
React 具有强大的组合模型,推荐使用组合而不是继承来重用组件之间的代码。
道具和组合为您提供了以明确和安全的方式自定义组件外观和行为所需的所有灵活性。请记住,组件可以接受任意道具,包括原始值、React 元素或函数。
你应该像下面这样使用它。
错误组件
export default class ErrorComponent extends Component {
constructor(props) {
super(props);
this.setState({...this.props.childState });
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
然后BaseForm
用ErrorComponent
.
export default class BaseForm extends Component {
constructor(props) {
super(props);
this.setState({
reason: null
});
}
render() {
return (
<ErrorComponent childState={this.state}>
<div>
some thing
</div>
</ErrorComponent>
)
}
}
你可以阅读更多关于React 中的组合与继承的信息
推荐阅读
- oauth-2.0 - Cognito OAuth2 access code handling with a desktop app
- apache-kafka - 从主题创建表并得到一些关于 LongDeserializer 接收的数据大小的序列化异常不是 8
- algorithm - 在 BTreeMap 中获取最大值的键的惯用方法?
- android - DevicePolicyManager 抛出 SecurityException
- c++ - 为什么 ceil() 函数返回意外值?
- node.js - 如何在 express.js 中的路由之间传递数据
- r - `vec_assign()` 的错误是什么:`value` 应该被回收以适应 `x`。试图告诉我
- c++ - 有没有办法在用 C++ 读取文件时忽略文件结尾字符?
- node.js - 我正在尝试在发生错误后在本地安装节点。我尝试了几次重新安装节点,但仍然显示错误
- javascript - 承诺递归 | 异步画布绘画