简体   繁体   English

React 是怎么知道 this.props 的?

[英]How does React know this.props?

When I watch tutorials they try to read this.props without defining the term props anywhere.当我看教程时,他们试图阅读this.props而没有在任何地方定义术语props Is props a keyword?道具是关键字吗? If not how does React know that it is props without defining it anywhere in the code?如果不是,React 怎么知道它是 props 而不在代码中的任何地方定义它?

No, props isn't a keyword.不, props不是关键字。 The React.Component constructor receives the props object (because React.createElement passes them to the component function as the first argument; JSX generates the calls to React.createElement ) and assigns props to the instance being created, like this: React.Component构造函数接收道具 object(因为React.createElement将它们作为第一个参数传递给组件 function;JSX 生成对React.createElement的调用)并将props分配给正在创建的实例,如下所示:

constructor(props) {
//          ^^^^^−−−−−−−−−−− parameter
    this.props = props;
//  ^^^^^^^^^^^^^^^^^^−−−−−− assignment
    // ...
}

That's why if you create your own constructor, you have to pass the object you receive as the first parameter to super like this:这就是为什么如果您创建自己的构造函数,则必须将收到的 object 作为第一个参数传递给super ,如下所示:

class MyComponent extends React.Component {
    constructor(props) {
       super(props);
//           ^^^^^^−−−−−−−−− passing them on to `super`
        // ...
    }
}

i don't know the technical details, (because i don't need to) but just know that whenever you use a react component (class based, or function based) some parameters get passed into the react component, and you guessed it, props got all of the parameters.我不知道技术细节,(因为我不需要)但只知道每当你使用反应组件(基于类,或基于 function)时,一些参数会传递到反应组件中,你猜对了, props 得到了所有的参数。

So if you wish to see what are the parameters in props you can just因此,如果您想查看 props 中的参数是什么,您可以

console.log(this.props)

one of the most parameters that props has: are the ones you pass around yourself from a react component, to its child react component. props 拥有最多的参数之一:是您从反应组件传递到其子反应组件的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM