问题描述
我在使用带有对象数组的propTypes创建React Components时遇到一些问题。
所以我有这个对象数组:
var movies = [ { id: 1, title: "Harry Potter", desc: "Wizzard Movie", src: "https://ocdn.eu/pulscms-transforms/1/isDktkqTURBXy9kMmM4YmI4N2QzY2U0ZjI5NmIzNTU3Mjk2ZTg2ZWY2My5qcGVnkZMCAM0B5A" }, { id: 2, title: "LK", desc: "Movie about Lion King", src: "https://1.fwcdn.pl/an/np/1985708/2016/5817_1.7.jpg" }, { id: 3, title: "Pulp Fiction", desc: "xxx", src: "https://coubsecure-s.akamaihd.net/get/b44/p/coub/simple/cw_timeline_pic/2d2d519173e/5f0067e9d4849ef1dee4a/big_1518161198_image.jpg" }, { id: 4, title: "Lethal Weapon 3", desc: "Movie about..", src: "https://media.teleman.pl/photos/lethal-weapon-3.jpg" } ];
我想做的是:1.为要创建的每个组件创建类:-电影类应具有:标题,说明和图像。 所以我必须为每个元素(标题,desc,img)制作propType吗?
var Movie = React.createClass({ render: function() { return ( React.createElement( "li", { key: movie.id }, React.createElement(MovieTitle, {}), React.crreateElement("p", {}, this.props.movie.desc), React.createElement("img", { src: this.props.movie.src }) )); }, propTypes: { image: React.PropTypes.object.isRequired, des: React.PropTypes.object.isRequired, title: React.PropTypes.object.isRequired } });
- Movie Title Class
var MovieTitle = React.createClass({ render: function() { return React.createElement("h2", {}, this.props.movie.title); }, propTypes: { title: React.PropTypes.object.isRequired } });
- MovieDescription Class
var MovieDescription = React.createClass({ render: function() { return React.createElement("p", {}, this.props.movie.desc); }, propTypes: { desc: React.PropTypes.object.isRequired } });
- Movie Image Class
var MovieImage = React.createClass({ render: function() { return React.createElement("img", {src: this.props.movie.src}) }, propTypes: { image: React.ProTypes.object.isRequired } });
我想对对象数组进行映射,并创建“电影元素”,然后将它们放入渲染中,然后将整个列表放入div#app。
- 问题是,我可以使用movies.map方法来制作它,并使每个元素带有一个“循环”。
var moviesElements = movies.map(function(movie) { return React.createElement( "li", { key: movie.id }, React.createElement("h2", {}, movie.title), React.createElement("p", {}, movie.desc), React.createElement("img", {}, movie.src) ); });
var element = React.createElement( "div", {}, React.createElement("h1", {}, "List of movies"), React.createElement("ul", {}, moviesElements) ); ReactDOM.render(element, document.getElementById("app"));
但是我不知道如何处理所有这些由类和propTypes组成的组件。
我将不胜感激:)
1楼
Martin Prins
1
已采纳
2019-02-20 21:27:08
您可以将其映射到电影上并使用class组件作为第一个参数来创建react元素。
var moviesElements = movies.map(function(movie) {
return React.createElement(Movie, {movie: movie});
});
我制作了一个 (还修复了您共享的代码中的某些拼写错误和缺少的参数)