React - 如何在不使用构造函数的情况下访问道具 [英] React - How to access props without using constructor

查看:96
本文介绍了React - 如何在不使用构造函数的情况下访问道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我使用React Native遇到了这个特定的问题,但我想这也适用于React。

Note: I encounter this specific problem using React Native, but I guess this goes for React in general as well.

我有一个使用React构建的react组件。零件。
我不需要设置状态,但我确实有道具。我提出的语法如下:

I have a react component built using React.Component. I don't need to set state, but I do have props. My proposed syntax was as follows:

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

我知道我可以用一个函数来构造这个组件,像这样:

I understand I can use a function to construct this component, like this:

const Header = (props) => {
  return <div>{props.title}</div>;
}

但我更喜欢前者,因为我的组件会增长,可能有州等,我只是想以类似的方式保持所有组件的构建。

But I prefer the former, because my component will grow, might have state etc, and I just want to keep all my components built in a similar fashion.

现在,我的linter抱怨有一个无用的构造函数,但我怎么去访问道具保持类构造函数而不是函数构造函数?

Now, my linter complains about having a useless constructor, but how else do I access the props while keeping a class constructor instead of a function constructor?

推荐答案


如果你想使用它。在构造函数中的props,你需要将props传递给super。否则,没关系,因为React在调用构造函数后立即从外部设置.props。

If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn't matter because React sets .props on the instance from the outside immediately after calling the constructor.

所以只是简单如果没用,删除构造函数()

So just simply remove constructor() if useless

这篇关于React - 如何在不使用构造函数的情况下访问道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆