以下代码都在CmtItem.jsx文件中
1.样式的第一层封装,将样式对象和结构分离:
const itemStyle =
{
border: '1px dashed #ccc',
margin: '10px',
padding: '10px',
boxShadow: '0 0 10px #ccc'
}
const userStyle =
{
fontSize: '15px'
}
const conentStyle =
{
fontSize: '13px'
}
//使用function构造函数,定义普通的无状态组件
export default function CmtItem(props) {
return <div style={itemStyle} >
<h1 style={userStyle}>评论人:{props.user}</h1>
<p style={contentStyle}>评论内容:{props.conent}</p>
</div>
}
2.第二层封装,将所有的样式合并成一个大的模块
const style =
{
item:{border: '1px dashed #ccc',
margin: '10px',
padding: '10px',
boxShadow: '0 0 10px #ccc'
},
user: { fontSize: '15px' },
content:{ fontSize: '13px'}
}
export default function CmtItem(props) {
return <div style={styles.item} >
<h1 style={styles.user}>评论人:{props.user}</h1>
<p style={styles.content}>评论内容:{props.conent}</p>
</div>
}
3.第三层封装:抽离为单独的样式表模块
在src下新建文件styles.js,在文件中写入:
export default{
item:{border: '1px dashed #ccc',
margin: '10px',
padding: '10px',
boxShadow: '0 0 10px #ccc'
},
user: { fontSize: '15px' },
content:{ fontSize: '13px'}
}
在CmtItem.jsx中导入
import styles from '@/components/styles'
//使用function构造函数,定义普通的无状态组件
export default function CmtItem(props) {
return <div style={styles.item} >
<h1 style={styles.user}>评论人:{props.user}</h1>
<p style={styles.content}>评论内容:{props.conent}</p>
</div>
}
4.CmtList.jsx文件中代码如下:
import React from 'react'
//导入评论项的子组件
import CmtItem from '@/Components/CmtItem'
//创建一个父组件
export default class CmtList extends React.Component{
constructor(){
super();
this.state = {
CommentList:[//评论列表数据
{id:1,user:'安琪拉',conent:'魔法为我而存在'},
{id:2,user:'后羿',conent:'发光的一个就够了'},
{id:3,user:'刘禅',conent:'一号机开启暴走状态'},
{id:4,user:'鲁班',conent:'有时候肌肉比头脑更厉害'},
{id:5,user:'吕布',conent:'我的貂蝉在哪里'}
]
}
}
render(){
return<div>
{/*
1.在jsx中如果想写行内样式,不能为style设置字符串的值,而应该
2.style = {{color:'red'}}
3.在行内样式中,如果是数值类型的样式,则可以不用引号包裹,如果是字符串类型的,则需要
*/}
<h1 style={{color:'red',fontSize:'35px',textAlign:'center',fontWeight:200}}>这是评论列表组件</h1>
{this.state.CommentList.map(item =><CmtItem {...item} key = {item.id}></CmtItem>)}
{/*上面的箭头函数相当于下面的这样写法
{this.state.CommentList.map(function(item){
{
return <CmtItem {...item} key={item.id}></CmtItem>
}
})
} */}
</div>}
}
5.结果为: