Topic: React components inherit custom components I. Requirements description
Description: There are a,b,c,d four components, there are some common logic, such as setting data, get data, there are some common properties, do not want to write these attributes in each component, how to do? "and the object-oriented language, C#,java's base class idea is the same"
If something is common, there are some ways that you can use React's Mixins (ES5), high-order components (ES6) "High- order functions are not well understood, how to use, to find the information "
But if there's a common attribute, then it's a little too much.
In the React, do you think you can inherit a custom component?
After searching for information, it is found that React is a component that can inherit its own definition.
Second, the solution
The steps to implement are simple, just
class Win extends React.Component
Replaced by
class Win extends BaseWin
1. Example code
import React from ‘react‘
/**
* 所有弹框的基类
*/
class BaseWin extends React.Component {
constructor(props) {
super(props);
this.name = ‘zhongxia‘;
this.state = {};
}
common() {
alert(‘this is a common function!‘)
}
}
export default BaseWin;
import React from ‘react‘
import BaseWin from ‘./baseWindow‘
class Win extends BaseWin {
constructor(props) {
super(props);
this.state = {
...this.props
};
console.log(this.name);
this.common();
}
getData() {
return this.state;
}
render() {
this.state.node.model.set({name: ‘zhongxia‘, age: 17})
return (
<div className="pop-dialog">
<h2>弹框1</h2>
<form>
<label htmlFor="">用户名:</label><input value={this.state.name} type="text"/>
<label htmlFor="">密码:</label><input type="password" value={this.state.password}/>
</form>
</div>
);
}
}
export default Win;
2. Instantiate the order of the React components and
Instantiate Subclass Component = = constructor inside super (prop) to instantiate the parent class component = = "Parent Component instantiation End = =" Subclass Component Instantiation End
Run by:
1. Sub-class constructors
2. Super (props) instantiation of the parent class
3. The subclass constructor ends and you can already get the properties and methods of the parent class
4. Subclass instances Start rendering the page
From for notes (Wiz)
#003 React component inherits a custom component