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

标签 reactjs typescript

我在 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.

最佳答案

不,你不需要。

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

const MyButton = (props) => {
  return (
    <div><button>{props.children}</button></div>
  );
};

关于reactjs - ReactJS 组件类是否需要构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441713/

相关文章:

reactjs - 任何人都可以与护照谷歌 oauth2 集成分享下一个 js 的例子吗?

css - 如何在 React App 中显示 Emoji

javascript - 将 Webpack 与 React-router bundle.js 一起使用未找到

typescript - 扩展和修改嵌套 typescript 接口(interface)

javascript - 什么是双箭头函数?

javascript - 从单独的文件导入动态 MaterialUI 主题对象?

reactjs - nextjs- typescript- 属性 'className' 在类型 'IntrinsicAttributes 和 IntrinsicClassAttributes 上不存在

javascript - TSLint 烦人的消息

html - 类型错误 : Cannot read property 'Classes' of undefined

javascript - 过滤数组中的元素在 Reactjs 中不起作用