我有一个反应组件,基本上是一个简单的滑块。
现在,滑块中的图像是硬编码的
以下是代码:
import React from 'react';
const Slider = () => (
<div>
<div id="myCarousel" className="carousel slide" data-ride="carousel">
<div className="carousel-inner" role="listbox">
<div className="item active">
<img src="http://placehold.it/1250x250" alt="Chania" />
</div>
<div className="item">
<img src="http://placehold.it/1250x250" alt="Chania" />
</div>
<div className="item">
<img src="http://placehold.it/1250x250" alt="Flower" />
</div>
<div className="item">
<img src="http://placehold.it/1250x250" alt="Flower" />
</div>
</div>
<a className="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span className="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span className="sr-only">Previous</span>
</a>
<a className="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span className="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span className="sr-only">Next</span>
</a>
</div>
<br /><br />
</div>
);
export default Slider;
我的问题是,如何将图片网址值传递给组件?
答案 0 :(得分:1)
创建一个图像数组,并通过props传递它:
import React from 'react';
const Slider = ({ images }) => (
<div>
<div id="myCarousel" className="carousel slide" data-ride="carousel">
<div className="carousel-inner" role="listbox">
<div>
{images.map(({ src, alt}) => (
<div className="item">
<img src="http://placehold.it/1250x250" alt="Flower" />
</div>
)}
</div>
<a className="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span className="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span className="sr-only">Previous</span>
</a>
<a className="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span className="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span className="sr-only">Next</span>
</a>
</div>
<br /><br />
</div>
);
export default Slider;
// example of usage in parent
class App extends Component {
constructor(props) {
super(props);
this.state = {
images: [
{ src: "http://placehold.it/1250x250", alt": "Chania" },
{ src: "http://placehold.it/1250x250", alt": "Chania" },
{ src: "http://placehold.it/1250x250", alt": "Flower" },
{ src: "http://placehold.it/1250x250", alt": "Flower" }
]
};
}
render() {
return (
<Slider images={ this.state.images } />
);
}
}