freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/override-default-props.chin...

2.7 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d403616c Override Default Props 6 false 覆盖默认道具

Description

设置默认道具的能力是React中的一个有用功能。覆盖默认道具的方法是显式设置组件的prop值。

Instructions

ShoppingCart组件现在呈现子组件Items 。此Items组件的默认prop quantity设置为整数0 。通过为quantity传递值10来覆盖默认支柱。 注意:请记住向组件添加prop的语法与添加HTML属性的方式类似。但是由于quantity的值是一个整数,因此它不会引用引号,但应该用大括号括起来。例如, {100} 。此语法告诉JSX将大括号内的值直接解释为JavaScript。

Tests

tests:
  - text: <code>ShoppingCart</code>应该呈现组件。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("ShoppingCart").length === 1; })(), "The component <code>ShoppingCart</code> should render.");'
  - text: 该组件<code>Items</code>应该呈现。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("Items").length === 1; })(), "The component <code>Items</code> should render.");'
  - text: '<code>Items</code>组件应具有从<code>ShoppingCart</code>组件传递的<code>{ quantity: 10 }</code>的prop。'
    testString: 'getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("Items").props().quantity == 10 && getUserInput("index").replace(/ /g,"").includes("<Itemsquantity={10}/>"); })(), "The <code>Items</code> component should have a prop of <code>{ quantity: 10 }</code> passed from the <code>ShoppingCart</code> component.");'

Challenge Seed

const Items = (props) => {
  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
}

Items.defaultProps = {
  quantity: 0
}

class ShoppingCart extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    { /* change code below this line */ }
    return <Items />
    { /* change code above this line */ }
  }
};

After Test

console.info('after the test');

Solution

// solution required