繁体   English   中英

在React.js中使用this.props和props有什么区别?

[英]What is the difference between using this.props and props in React.js?

我一直在交替使用this.propsprops ,并且在大多数情况下,它们之间似乎并没有太大的区别(据我所知)。

但是,最近我遇到了一些问题,这些问题使我觉得何时以及为什么在其他问题上使用一个问题。

这是我目前可互换使用的地方:

  constructor(props, context) {
    super(props, context);
    this.data    = props.card.data;
    this.dataLength = this.props.card.data.length;
  }

有什么区别,何时在另一处使用,又在哪里使用? 谢谢!

这完全取决于您使用的组件的类型。

const StatelessComponent = (props) => {
    return <div>{props.something}</div>;
}

class SomeComponent extends Component {
    constructor(props){
        super(props)
    }
    render() {
        return <div>{this.props.something}</div>;
    }
}

在这里,您会注意到,在无状态组件中,它只是一个常规函数,没有任何this上下文。 道具被传递给函数,因此我们已经可以访问它了。
当你有一个类,你有this背景下,道具生活。
在类的构造函数中,道具将传递给类的构造函数。 因此,在该构造函数的上下文中,props作为参数传递,并且是局部变量

我建议您坚持使用模式,当在其他this.props类的方法中使用props作为函数的参数传递给使用props的函数时,请使用this.props 这就是打算使用它的方式。 还有一些要说的是为了保持一致性,因此无论您选择带有该模式的一根棍子还是另一根棍子。 如果您不遵循模式/保持一致,可能会造成混乱。

只有在React ES2015组件(非功能组件)的constructor函数中,您才能在传递给构造函数时引用props 如果在constructor执行this.props === props ,它将评估为true

但是在React中,您只能在调用super(props)之后使用this.props 这是ES2015 Class规范的一部分

为简单起见,我通常只在constructor仅使用props ,而在组件生命周期方法和render仅使用this.props

简单来说:

  • 1.props.data用于功能组件2.this.props.data用于类组件

复制代码并在“ stackblitz”中运行-> https://stackblitz.com/edit/react-3wr8jb

以下代码显示了props.data和this.props.data中类和功能组件的用法

import React, { Component } from 'react';
import { render } from 'react-dom';

//=================PROPS=======================
//Both Class and Functional components have "properties" ie props
//properties are immutable->fixed->cant be changed

//=================================================
//props.data in functional components
function A1(props)
{
  return <h2>functional component->props.data:{props.data}</h2>
}
//===============================================
//this.props.data in class components
class A2 extends React.Component{
  render()
  {
    return<h2>class component->this.props.data:{this.props.data}</h2>
  }
}
//===================================================
var element1=
<div>
<hr/>
//data from class and functional component
<A1 data="Sample data" />
<A2 data="Sample data"></A2>
<hr />
</div>


render(element1, document.getElementById('root'));

暂无
暂无

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

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