1.5 KiB
1.5 KiB
title | localeTitle |
---|---|
Write a React Component from Scratch | 从Scratch写一个React组件 |
从Scratch写一个React组件
在这个挑战中,我们想要创建一个class
反应组件(React组件可以是class
组件或function
组件)。我们所有的类组件都将成为React.Component
的扩展。例如,我们可以开始创建一个名为FirstComponent
的组件:
class FirstComponent extends React.Component {
};
我们还需要确保为新类定义constructor
。最好使用super
调用任何组件的constructor
,并将props
传递给它们。 super
拉取组件父类的constructor
(在本例中为React.Component
)。现在,我们组件的代码如下所示:
class FirstComponent extends React.Component {
constructor(props) {
super(props);
}
};
现在剩下要做的就是定义我们的组件将render
!我们通过调用组件的render
方法并返回我们的JSX代码来实现:
class FirstComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
// The JSX code you put here is what your component will render
);
}
};
一旦你的JSX代码在那里,你的组件就完成了!如果你想要一个更精细的React组件教程,那么Samer Buna 写了一篇很棒的文章 。