在具有自动绑定和 属性 初始化器的 React 中是否仍然需要构造函数
Is the constructor still needed in React with autobinding and property initializers
我正在重构一个基于 es6 class 的 React 组件,它使用普通构造函数,然后绑定方法,并在该构造函数中定义 state/attributes。像这样:
class MySpecialComponent extends React.Component {
constructor(props) {
super(props)
this.state = { thing: true }
this.myMethod = this.myMethod.bind(this)
this.myAttribute = { amazing: false }
}
myMethod(e) {
this.setState({ thing: e.target.value })
}
}
我想重构它,以便自动绑定函数,并使用 属性 初始值设定项作为状态和属性。现在我的代码看起来像这样:
class MySpecialComponent extends React.Component {
state = { thing: true }
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
}
我的问题是,我还需要构造函数吗?还是道具也是自动绑定的?我原以为仍然需要构造函数并包含 super(props)
,但我的代码似乎可以正常工作,但我很困惑。
谢谢
您不需要明确定义的构造函数,除非您需要在初始状态对象中引用 props
。
您无需显式定义构造函数,然后执行 super(props)。您可以按照以下示例访问道具。即 'prop1'
class MySpecialComponent extends React.Component {
state = {
thing: true ,
prop1:this.props.prop1
}
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
render(){
console.log(this.state.prop1);
return(
<div>Hi</div>
);
}
}
ReactDOM.render(<MySpecialComponent prop1={1}/> , mountNode);
据我了解,使用 class properties 时根本不需要输入构造函数(如第二个代码示例中所示)。接受的答案指出,如果你 "need to reference the props in your initial state object," 你确实需要一个,但如果你使用所述 class 属性,那么你可能正在使用 Babel 来转换它,在这种情况下构造函数 是使用的,它只是在幕后完成的。正因为如此,你不需要自己添加构造函数,即使你在 state 中使用 props。
有关更好的示例和更好的解释,请参阅 this aricle。
我正在重构一个基于 es6 class 的 React 组件,它使用普通构造函数,然后绑定方法,并在该构造函数中定义 state/attributes。像这样:
class MySpecialComponent extends React.Component {
constructor(props) {
super(props)
this.state = { thing: true }
this.myMethod = this.myMethod.bind(this)
this.myAttribute = { amazing: false }
}
myMethod(e) {
this.setState({ thing: e.target.value })
}
}
我想重构它,以便自动绑定函数,并使用 属性 初始值设定项作为状态和属性。现在我的代码看起来像这样:
class MySpecialComponent extends React.Component {
state = { thing: true }
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
}
我的问题是,我还需要构造函数吗?还是道具也是自动绑定的?我原以为仍然需要构造函数并包含 super(props)
,但我的代码似乎可以正常工作,但我很困惑。
谢谢
您不需要明确定义的构造函数,除非您需要在初始状态对象中引用 props
。
您无需显式定义构造函数,然后执行 super(props)。您可以按照以下示例访问道具。即 'prop1'
class MySpecialComponent extends React.Component {
state = {
thing: true ,
prop1:this.props.prop1
}
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
render(){
console.log(this.state.prop1);
return(
<div>Hi</div>
);
}
}
ReactDOM.render(<MySpecialComponent prop1={1}/> , mountNode);
据我了解,使用 class properties 时根本不需要输入构造函数(如第二个代码示例中所示)。接受的答案指出,如果你 "need to reference the props in your initial state object," 你确实需要一个,但如果你使用所述 class 属性,那么你可能正在使用 Babel 来转换它,在这种情况下构造函数 是使用的,它只是在幕后完成的。正因为如此,你不需要自己添加构造函数,即使你在 state 中使用 props。
有关更好的示例和更好的解释,请参阅 this aricle。