在使用带有对象数组的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。
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组成的组件。
感谢您的帮助:)
答案 0 :(得分:1)
您只需将影片映射并使用class组件作为第一个参数来创建react元素即可。
var moviesElements = movies.map(function(movie) {
return React.createElement(Movie, {movie: movie});
});
我做了一个code sandbox example(还修复了您共享代码中的一些错别字和缺少的参数)