我们可以在 React 中用其他名称调用 constructor(props) 吗?
Can we call constructor(props) with other names in react?
constructor(props) {
super(props);
学习react,我经常遇到这两行。我明白必须写 super 才能使用“this”方法。但是为什么我们总是用"props"这个词呢?如果我们的 class 持有关于人的信息并且我们想要传递:(年龄、姓名、工作)怎么办?
以下代码有效吗?
constructor(Age, Name, Job) {
super(Age, Name, Job);
如果不是,"props" 会在 React.Component 内部触发什么?
道具中还有React.Component需要的其他信息,所以你必须调用super(props)否则React.Component将无法获得这些重要信息。
但这并不妨碍您在构造函数中使用其他数据,它们可以作为道具传递:props.age、props.name...
React Component
class 期望其构造函数有 3 个参数:props
、context
和 updater
.
你可以做到
constructor(Age, Name, Job) {
super(Age, Name, Job);
但你必须记住,你只是在这里重命名 props
、context
和 updater
,并没有做任何特别的事情。
当你传递像
这样的道具时
<MyComponent age={age} name={name} />
它们可作为 props
的属性使用。在 constructor
中,您可以像这样访问它们:
constructor(props){
super(props);
console.log('age', props.age);
console.log('name', props.name);
}
constructor(props) {
super(props);
学习react,我经常遇到这两行。我明白必须写 super 才能使用“this”方法。但是为什么我们总是用"props"这个词呢?如果我们的 class 持有关于人的信息并且我们想要传递:(年龄、姓名、工作)怎么办? 以下代码有效吗?
constructor(Age, Name, Job) {
super(Age, Name, Job);
如果不是,"props" 会在 React.Component 内部触发什么?
道具中还有React.Component需要的其他信息,所以你必须调用super(props)否则React.Component将无法获得这些重要信息。
但这并不妨碍您在构造函数中使用其他数据,它们可以作为道具传递:props.age、props.name...
React Component
class 期望其构造函数有 3 个参数:props
、context
和 updater
.
你可以做到
constructor(Age, Name, Job) {
super(Age, Name, Job);
但你必须记住,你只是在这里重命名 props
、context
和 updater
,并没有做任何特别的事情。
当你传递像
这样的道具时<MyComponent age={age} name={name} />
它们可作为 props
的属性使用。在 constructor
中,您可以像这样访问它们:
constructor(props){
super(props);
console.log('age', props.age);
console.log('name', props.name);
}