React - 如何在不使用构造函数的情况下访问道具

React - How to access props without using constructor

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

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

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

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

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

但我更喜欢前者,因为我的组件会增长,可能有状态等,我只想让我的所有组件都以类似的方式构建。

现在,我的 linter 抱怨有一个无用的构造函数,但是在保留 class 构造函数而不是函数构造函数的同时,我还能如何访问道具?

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.

所以如果没用就简单地删除 constructor()

您可以使用 "this" 在 class 中访问没有构造函数的道具,如下所示:

class XXXXXX extends React.Component {
   render() {
       return (
          <div>{this.props.value}</div>
       )
   }
}