react 中 super() 和 super(props)的区别
时间: 2024-04-02 13:31:50 浏览: 16
在 React 中,`super()`和`super(props)`都用于调用父类的构造函数。但是,它们之间有一些区别。
当你使用`super()`时,它会将`this`传递给父类的构造函数,并且在构造函数中你不能访问`this.props`。这意味着,如果你需要在构造函数中访问`this.props`,那么你需要使用`super(props)`。
当你使用`super(props)`时,它会将`this`和`props`都传递给父类的构造函数,并且父类的构造函数可以通过`this.props`访问传递进来的`props`属性。
因此,如果你需要在构造函数中访问`props`属性,那么你应该使用`super(props)`。否则,如果你不需要在构造函数中访问`props`属性,那么你可以使用`super()`。
相关问题
react中怎么改变this.props中的值
在 React 中,this.props 属性是只读的,不能直接修改其值。如果需要修改传递给组件的 props,应该通过在父组件中修改对应的 state,然后再通过 props 将修改后的值传递给子组件。
具体来说,可以在父组件中定义一个 state,然后将需要修改的值作为 state 的属性。然后在父组件中定义一个方法,用于修改 state 中的属性值。最后将 state 中的属性通过 props 传递给子组件,在子组件中使用 props 显示对应的值。
例如,在父组件中定义一个 state,其中包含一个名为 count 的属性:
```
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
// 定义一个方法用于修改 count 值
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<ChildComponent count={this.state.count} />
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
```
在子组件中,通过 props 显示 count 值:
```
class ChildComponent extends React.Component {
render() {
return (
<div>{this.props.count}</div>
);
}
}
```
此时,点击父组件中的按钮可以修改 count 值,并将新的值通过 props 传递给子组件,从而更新子组件中显示的值。
super(props)
这是在 React 中用于在子类 constructor 中调用父类 constructor 的语法。它的作用是继承父组件的属性和方法。在使用 ES6 class 定义组件时,如果需要在子类的 constructor 中访问 this.props,就必须在 constructor 中调用 super(props)。