假设有一个父组件
/* eslint-disable array-callback-return */
import React from 'react'
import ReactDOM from 'react-dom'
// 引入子组件
class Element extends React.Component {
state = {
list: [
{ id: 1, name: '棒棒糖', price: 18, num: 1 },
{ id: 2, name: '大鸡腿', price: 34, num: 2 },
{ id: 3, name: '冰激凌', price: 14, num: 3 }
]
}
render () {
// 解构
const { list } = this.state
return (
<div
style={{
border: '1px solid #ccc',
margin: 10,
padding: 10,
width: 500
}}>
<h3>商品列表</h3>
{list.map((item) => (
<div style={{border:'1px solid #ccc', margin:10 ,padding:10 ,width:500}} key={item.id} >
<p>名称:{item.name}</p>
<p>单价:{item.price}</p>
<p>数量:{item.num}</p>
<p>总价:{item.price * item.num}</p>
</div>
))}
<p>
总价:1000
</p>
</div>
)
}
}
ReactDOM.render(<Element />, document.getElementById('root'))
## 1.组件拆分 (确定需要拆分的部分)
```css
<div style={{border:'1px solid #ccc', margin:10 ,padding:10 ,width:500}} key={item.id} >
<p>名称:{item.name}</p>
<p>单价:{item.price}</p>
<p>数量:{item.num}</p>
<p>总价:{item.price * item.num}</p>
</div>
2.确定好要拆分的部分 ,创建一个子组件
import React, { Component } from 'react'
export default class GoodItem extends Component {
render() {
console.log(this.props.good)
const { good} =this.props
return (
<div style={{border:'1px solid #ccc', margin:10 ,padding:10 ,width:500}} >
<p>名称:{good.name}</p>
<p>单价:{good.num}</p>
<p>数量:{good.price}</p>
<p>总价:{good.price * good.num}</p>
</div>
)
}
}
## 3.向子组件传递 good ,循环 设置key值
引入子组件
```css
import React from 'react'
import ReactDOM from 'react-dom'
import GoodItem from './GoodItem'
// 引入子组件
class Element extends React.Component {
state = {
list: [
{ id: 1, name: '棒棒糖', price: 18, num: 1 },
{ id: 2, name: '大鸡腿', price: 34, num: 2 },
{ id: 3, name: '冰激凌', price: 14, num: 3 }
]
}
render () {
// 解构
const { list } = this.state
return (
<div
style={{
border: '1px solid #ccc',
margin: 10,
padding: 10,
width: 500
}}>
<h3>商品列表</h3>
{list.map((item) => <GoodItem good={item} key={item.id} />)}
<p>
总价:{list.reduce((acc,cur) => {return acc + cur.price * cur.num},0)}
</p>
</div>
)
}
}
ReactDOM.render(<Element />, document.getElementById('root'))
4.在子组件接受 解构下 good
import React, { Component } from 'react'
export default class GoodItem extends Component {
render() {
console.log(this.props.good)
// eslint-disable-next-line no-unused-vars
const { good} =this.props
return (
<div style={{border:'1px solid #ccc', margin:10 ,padding:10 ,width:500}} >
<p>名称:{good.name}</p>
<p>单价:{good.num}</p>
<p>数量:{good.price}</p>
<p>总价:{good.price * good.num}</p>
</div>
)
}
}