ReactJS 组件类是否需要构造函数

Lam*_*ert 2 typescript reactjs

我在 Typescript 中使用 ReactJS。我需要下面的“构造函数”代码吗?没有它它也能正常工作,我查看了转换后的 JavaScript,它似乎无论如何都会自动添加它。

interface myProps {
   children?: any;
}
class MyButton extends React.Component<myProps, {}> {
    constructor(props: myProps) { //Needed ???
        super(props);
    }

    render() {
        return (<div>
            <button>
                {this.props.children}
            </button>
        </div>);
    } //end render.
} //end class.
Run Code Online (Sandbox Code Playgroud)

man*_*mat 5

不,你不需要。

实际上,您可以将这样的简单组件编写为函数。

const MyButton = (props) => {
  return (
    <div><button>{props.children}</button></div>
  );
};
Run Code Online (Sandbox Code Playgroud)