freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/render-state-in-the-user-in...

2.9 KiB
Raw Blame History

id title challengeType forumTopicId dashedName
5a24c314108439a4d4036172 以另一种方式在用户界面中渲染状态 6 301408 render-state-in-the-user-interface-another-way

--description--

还有另一种方法可以访问组件中的state。在render()方法中,在return语句之前,你可以直接编写 JavaScript。例如你可以声明函数、从stateprops访问数据、对此数据执行计算等。然后,你可以将任何数据赋值给你在return语句中可以访问的变量。

--instructions--

MyComponent的 render 方法中,定义一个名为name常量,并将其设置为组件state中的 name 值。因为可以直接在代码部分编写 JavaScript所以不需要用大括号括起来。

接下来,在 return 语句中,在h1标签中渲染变量name的值。记住,在 return 语句中需要使用 JSX 语法(用到 JavaScript 的花括号)。

--hints--

MyComponent应该有一个键name,其值freeCodeCamp存储在其 state 中。

assert(
  Enzyme.mount(React.createElement(MyComponent)).state('name') ===
    'freeCodeCamp'
);

MyComponent应该在div中渲染一个h1标题。

assert(
  /<div><h1>.*<\/h1><\/div>/.test(
    Enzyme.mount(React.createElement(MyComponent)).html()
  )
);

渲染的h1标签应该包含{name}的引用。

(getUserInput) =>
  assert(/<h1>\n*\s*\{\s*name\s*\}\s*\n*<\/h1>/.test(getUserInput('index')));

渲染的h1标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。

async () => {
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250));
  const mockedComponent = Enzyme.mount(React.createElement(MyComponent));
  const first = () => {
    mockedComponent.setState({ name: 'TestName' });
    return waitForIt(() => mockedComponent.html());
  };
  const firstValue = await first();
  assert(firstValue === '<div><h1>TestName</h1></div>');
};

--seed--

--after-user-code--

ReactDOM.render(<MyComponent />, document.getElementById('root'))

--seed-contents--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'freeCodeCamp'
    }
  }
  render() {
    // Change code below this line

    // Change code above this line
    return (
      <div>
        { /* Change code below this line */ }

        { /* Change code above this line */ }
      </div>
    );
  }
};

--solutions--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'freeCodeCamp'
    }
  }
  render() {
    // Change code below this line
    const name = this.state.name;
    // Change code above this line
    return (
      <div>
        { /* Change code below this line */ }
        <h1>{name}</h1>
        { /* Change code above this line */ }
      </div>
    );
  }
};