freeCodeCamp/guide/chinese/certifications/front-end-libraries/react/write-a-react-component-fro.../index.md

1.5 KiB
Raw Blame History

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 写了一篇很棒的文章