Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/write-a-react-component-from-scratch.md
Oliver Eyton-Williams ee1e8abd87 feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

2.4 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a24c314108439a4d4036168 从零开始写一个 React 组件 6 301424 write-a-react-component-from-scratch

--description--

现在你已经了解了 JSX 和 React 组件的基础知识现在是时候自己编写一个组件了。React 组件是 React 应用程序的核心组成部分,因此熟练编写它们是非常重要的。记住,典型的 React 组件是 ES6class,它扩展了React.Component。它有一个返回 HTML从 JSX 返回)或null的渲染方法,这是 React 组件的基本形式。一旦你深刻地理解了这一点,你就可以开始构建更复杂的 React 项目了。

--instructions--

定义一个MyComponent类,它是React.Component的扩展。它的渲染方法应该返回一个div,其中包含一个h1标签,标签文本为:My First React Component!。请确保文本内容、大小写和标点符号正确,以及调用了组件的构造函数。

使用ReactDOM.render()把该组件渲染到 DOM 中。有一个id='challenge-node'div可供你使用。

--hints--

应该有一个名为MyComponent的React组件。

(getUserInput) =>
  assert(
    getUserInput('index')
      .replace(/\s/g, '')
      .includes('classMyComponentextendsReact.Component{')
  );

MyComponent应该包含一个h1标签,标签的文本为My First React Component!,区分大小写并有标点符号。

assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(MyComponent));
    return mockedComponent.find('h1').text() === 'My First React Component!';
  })()
);

MyComponent应该渲染到 DOM。

assert(document.getElementById('challenge-node').childNodes.length === 1);

MyComponent 应该有一个构造器,里面调用了传参 propssuper 函数。

assert(
  MyComponent.toString().includes('MyComponent(props)') &&
    MyComponent.toString().includes('_super.call(this, props)')
);

--seed--

--seed-contents--

// Change code below this line

--solutions--

// Change code below this line
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>My First React Component!</h1>
      </div>
    );
  }
};

ReactDOM.render(<MyComponent />, document.getElementById('challenge-node'));