React - 如何在不使用constuctor的情况下访问道具

Sve*_*ies 8 javascript reactjs eslint react-native

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

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

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

我知道我可以使用一个函数来构造这个组件,如下所示:

const Header = (props) => {
  return <div>{props.title}</div>;
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 12

如果要在构造函数中使用this.props,则需要将props传递给super.否则,它无关紧要,因为在调用构造函数后,React会立即从外部设置.props.

所以,如果没用,只需删除constructor()即可