使用ES7 class語法谣殊,bootstrapV4作為css樣式
父組件
// 父組件 ProductsList.js
import React, { Component } from 'react';
import Product from './Product';
const products = [
{
id: 1,
imgUrl: 'http://fillmurray.com/200/100',
title: 'apple pie',
description: 'an apple a day keep a doctor away',
votes: 55
},
{
id: 2,
imgUrl: 'http://fillmurray.com/200/100',
title: 'orange juice',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id saepe,
ratione veritatis debitis minima, alias explicabo. Possimus nostrum consequuntur
dolorum, rem ipsum cupiditate expedita eligendi, iure temporibus odit quaerat minus.',
votes: 12
},
{
id: 3,
imgUrl: 'http://fillmurray.com/200/100',
title: 'time machine',
description: 'how to make a time machine, so we can go back and look forward',
votes: 66
},
{
id: 4,
imgUrl: 'http://fillmurray.com/200/100',
title: 'big bang of throey',
description: 'why stephen is so funny guy',
votes: 8
}
]
export default class ProductsList extends Component {
state = { // 狀態(tài)
products: products
}
handleVoteUp = (productId) => { // 處理子組件上的自定義 'onVoteUp' 事件
const nextProducts = this.state.products.map((product) => {
if (product.id === productId) { // 根據(jù) id 來判斷是哪個(gè)組件發(fā)生該事件
return { ...product, votes: product.votes + 1 }
} else {
return product;
}
});
this.setState({
products: nextProducts
});
}
handleVoteDown = (productId) => { // 處理子組件上的自定義 'onVoteDown' 事件
const nextProducts = this.state.products.map((product) => {
if (product.id === productId) {
return { ...product, votes: product.votes - 1 }
} else {
return product;
}
});
this.setState({
products: nextProducts
});
}
render() {
const productsList = this.state.products.map(product => (
// Product子組件 及 子組件上的屬性
<Product
key={'product-' + product.id}
id={product.id}
imgUrl={product.imgUrl}
title={product.title}
description={product.description}
votes={product.votes}
onVoteUp={this.handleVoteUp}
onVoteDown={this.handleVoteDown}
/>
));
return (
<ul className="list-unstyled" style={{width: 800}}>
{ productsList }
</ul>
)
}
}
子組件
// 父組件以屬性的形式,將狀態(tài)傳遞給子組件
// Product.js
import React, { Component } from 'react';
export default class Product extends Component {
voteUp = () => { // click 事件的handler
this.props.onVoteUp(this.props.id) // 調(diào)用屬性上的 'onVoteUp' 方法
}
voteDown = () => {
this.props.onVoteDown(this.props.id) // 調(diào)用屬性上的 'onVoteDown 方法
}
render() {
const { imgUrl, title, description, votes } = this.props;
return (
<li className="media" style={{marginTop: 20}}>
<img className="d-flex mr-3" src={imgUrl} alt="image"/>
<div className="media-body">
<h5 className="mt-0">{ title }</h5>
{ description }
<div>
{ votes }
<button onClick={this.voteUp}>投票 UP</button>
<button onClick={this.voteDown}>投票 DOWN</button>
</div>
</div>
</li>
)
}
}
app.js
import React, { Component } from 'react';
import ProductsList from './ProductsList';
class App extends Component {
render() {
return (
<ProductsList />
);
}
}
export default App;