我正在尝试更熟悉使用 React 的最佳实践和设计模式,但我有一个问题,即两个相似的解决方案中哪一个是正确的:
第一个解决方案使用了一个不扩展组件的类,它的构造函数返回一个基于对象的元素集,看起来更简洁一些,整体代码更少。
class PostEntryElement {
constructor(postObjectArray) {
return (
postObjectArray.map((postObject, index) => {
return (
<li style={{marginTop: '20px'}}>
Author: {postObject.author},
Body: {postObject.body},
Created: {postObject.created},
Title: {postObject.title}
</li>
)
})
)
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
exampleAPIBlogPostsResponse: [
{
title : 'Title 1',
body : 'Body 1',
author : 'Author 1',
created: 'Created 1'
}, {
title : 'Title 2',
body : 'Body 2',
author : 'Author 2',
created: 'Created 2'
}, {
title : 'Title 3',
body : 'Body 3',
author : 'Author 3',
created: 'Created 3'
}
]
};
}
render() {
return (
<div>
See All Posts Below:
<div>
{
this.state.exampleAPIBlogPostsResponse &&
new PostEntryElement(this.state.exampleAPIBlogPostsResponse)
}
</div>
</div>
);
}
}
React.render(<MyComponent />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
第二种解决方案使用带有属性的自定义组件,并从对象中动态传递它们,但代码更多而且看起来不那么“干净”。
class PostEntryElement extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<li style={{marginTop: '20px'}}>
Author: {this.props.author},
Body: {this.props.body},
Created: {this.props.created},
Title: {this.props.title}
</li>
);
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
exampleAPIBlogPostsResponse: [
{
title : 'Title 1',
body : 'Body 1',
author : 'Author 1',
created: 'Created 1'
}, {
title : 'Title 2',
body : 'Body 2',
author : 'Author 2',
created: 'Created 2'
}, {
title : 'Title 3',
body : 'Body 3',
author : 'Author 3',
created: 'Created 3'
}
]
};
}
generatePosts() {
return (this.state.exampleAPIBlogPostsResponse.map((postObject, index) => {
return (
<PostEntryElement
title={postObject.title}
body={postObject.body}
author={postObject.author}
created={postObject.created}
/>
)
})
);
}
render() {
return (
<div>
See All Posts Below:
<div>
{this.state.exampleAPIBlogPostsResponse && this.generatePosts()}
</div>
</div>
);
}
}
React.render(<MyComponent />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
最佳答案
在 React 中,你的状态应该由容器组件管理。容器通常应该是扩展 Component
的类。展示组件应该是根据容器提供的属性呈现的无状态纯函数。
如果您有兴趣,Thinking in React很好地介绍了 React,以及组件应该如何相互交互。
关于javascript - ReactJS 设计模式——类与自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566556/