Javascript 基于类的组件中的状态应该在构造函数内部或外部,在这两种情况下有所不同[React]
在使用Javascript 基于类的组件中的状态应该在构造函数内部或外部,在这两种情况下有所不同[React],javascript,html,reactjs,state,Javascript,Html,Reactjs,State,在使用React时,我看到在基于类的组件中,状态以两种方式添加:要么在构造函数内部,有时在构造函数外部(没有编写构造函数)。我很困惑,生成状态的正确方法是什么?另外,添加状态对象的两种方式(构造函数内部和外部)之间有什么区别?有什么建议吗 案例一: import React, {Component} from 'react'; class Home extends Component { constructor(props){ super(props); this.state = {
React
时,我看到在基于类的组件中,状态以两种方式添加:要么在构造函数内部,有时在构造函数外部(没有编写构造函数)。我很困惑,生成状态的正确方法是什么?另外,添加状态对象的两种方式(构造函数内部和外部)之间有什么区别?有什么建议吗
案例一:
import React, {Component} from 'react';
class Home extends Component {
constructor(props){
super(props);
this.state = {
list: ['red', 'green', 'blue']
};
}
render(){
return (
<div>hi</div>
);
}
}
export default Home;
import React, {Component} from 'react';
class Home extends Component {
state = {
list: ['red', 'green', 'blue']
};
render(){
return (
<div>hi</div>
);
}
}
export default Home;
import React,{Component}来自'React';
类Home扩展组件{
建造师(道具){
超级(道具);
此.state={
列表:[“红色”、“绿色”、“蓝色”]
};
}
render(){
返回(
你好
);
}
}
导出默认主页;
案例二:
import React, {Component} from 'react';
class Home extends Component {
constructor(props){
super(props);
this.state = {
list: ['red', 'green', 'blue']
};
}
render(){
return (
<div>hi</div>
);
}
}
export default Home;
import React, {Component} from 'react';
class Home extends Component {
state = {
list: ['red', 'green', 'blue']
};
render(){
return (
<div>hi</div>
);
}
}
export default Home;
import React,{Component}来自'React';
类Home扩展组件{
状态={
列表:[“红色”、“绿色”、“蓝色”]
};
render(){
返回(
你好
);
}
}
导出默认主页;
状态的创建在这两种语言中基本相同,都是正确的语法。使用构造函数时,可以将组件的this
绑定到任何类函数(即非箭头函数)。