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

3.4 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036172 Render State in the User Interface Another Way 6 false 用户界面中的渲染状态另一种方式

Description

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

Instructions

MyComponent render方法中定义一个名为nameconst ,并将其设置为等于组件state的name值。因为您可以直接在代码的这一部分编写JavaScript所以您不必将此引用括在花括号中。接下来在return语句中使用变量nameh1标记中呈现此值。请记住您需要在return语句中使用JSX语法JavaScript的大括号

Tests

tests:
  - text: <code>MyComponent</code>应该有一个键<code>name</code> ,其<code>freeCodeCamp</code>值存储在其状态中。
    testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "freeCodeCamp", "<code>MyComponent</code> should have a key <code>name</code> with value <code>freeCodeCamp</code> stored in its state.");'
  - text: <code>MyComponent</code>应该渲染一个包含在单个<code>div</code>的<code>h1</code>标头。
    testString: 'assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), "<code>MyComponent</code> should render an <code>h1</code> header enclosed in a single <code>div</code>.");'
  - text: '渲染的<code>h1</code>标记应包含对<code>{name}</code>的引用。'
    testString: 'getUserInput => assert(/<h1>\n*\s*\{\s*name\s*\}\s*\n*<\/h1>/.test(getUserInput("index")), "The rendered <code>h1</code> tag should include a reference to <code>{name}</code>.");'
  - text: 渲染的<code>h1</code>标头应包含从组件状态呈现的文本。
    testString: '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>", "The rendered <code>h1</code> header should contain text rendered from the component&apos;s state."); };'

Challenge Seed

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>
    );
  }
};

After Test

console.info('after the test');

Solution

// solution required