4.0 KiB
4.0 KiB
id, challengeType, forumTopicId, title
id | challengeType | forumTopicId | title |
---|---|---|---|
5a24c314108439a4d403616f | 6 | 301411 | 复习如何使用 Props 和无状态函数组件 |
Description
React.Component
,但是不使用内部状态(下一个挑战中讨论)。最后,状态组件是指维护其自身内部状态的组件,它简称组件或 React 组件。
一种常见的应用模式是尽可能减少状态组件并创建无状态的函数组件。这有助于将状态管理包含到应用程序的特定区域。反过来,通过更容易地跟踪状态变化如何影响其行为,可以改进应用程序的开发和维护。
Instructions
CampSite
组件,它把Camper
组件渲染为自己的子组件。定义Camper
组件,并为其分配默认 props{ name: 'CamperBot' }
。你可以在Camper
组件内部渲染任何你想要的代码,但是要确保有一个p
元素,它只包含作为prop
传递的name
值。最后,在Camper
组件上定义propTypes
,要求提供name
作为 prop,并验证它是string
类型。
Tests
tests:
- text: 应该渲染<code>CampSite</code>组件。
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('CampSite').length === 1; })());
- text: 应该渲染<code>Camper</code>组件。
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('Camper').length === 1; })());
- text: <code>Camper</code>组件应该包含默认 props,它将字符串<code>CamperBot</code>赋值给关键字<code>name</code>。
testString: assert(/Camper.defaultProps={name:(['"`])CamperBot\1,?}/.test(code.replace(/\s/g, '')));
- text: <code>Camper</code>组件应该包含<code>string</code>类型的<code>name</code>prop。
testString: assert(/Camper.propTypes={name:PropTypes.string.isRequired,?}/.test(code.replace(/\s/g, '')));
- text: <code>Camper</code>组件应该包含一个<code>p</code>元素,元素内是来自prop<code>name</code>的唯一文本。
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('p').text() === mockedComponent.find('Camper').props().name; })());
Challenge Seed
class CampSite extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Camper/>
</div>
);
}
};
// change code below this line
Before Test
var PropTypes = {
string: { isRequired: true }
};
After Test
ReactDOM.render(<CampSite />, document.getElementById('root'))
Solution
class CampSite extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Camper/>
</div>
);
}
};
// change code below this line
const Camper = (props) => {
return (
<div>
<p>{props.name}</p>
</div>
);
};
Camper.propTypes = {
name: PropTypes.string.isRequired
};
Camper.defaultProps = {
name: 'CamperBot'
};