案例:评论列表组件
下面演示使用React创建一个简单的静态评论列表组件,在这个案例中,你将看到父组件如何向子组件传递数据以及如何在组件中书写样式。
React08.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React08</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel" src="components/React08.jsx"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
ReactDOM.render(
<CmtList />,
document.getElementById("app")
);
</script>
</body>
</html>
React08.jsx:
const styles = {
item: {border: "1px dashed #ccc", margin: "10px", padding: "10px", boxShadow: "0 0 10px #ccc"},
user: {fontSize: "16px"},
content: {fontSize: "14px"}
};
function CmtItem(props) {
return <div style={styles.item}>
<h1 style={styles.user}>评论人:{props.user}</h1>
<p style={styles.content}>评论内容:{props.content}</p>
</div>
}
class CmtList extends React.Component{
constructor(){
super();
this.state = {
CommentList: [
{id: 1, user: "张三", content: "哈哈,沙发"},
{id: 2, user: "李四", content: "哈哈,板凳"},
{id: 3, user: "王五", content: "哈哈,凉席"},
{id: 4, user: "赵六", content: "哈哈,砖头"},
{id: 5, user: "田七", content: "哈哈,楼下山炮"}
]
}
}
render(){
return <div>
<h1 style={{color: "red", fontSize: "35px", fontWeight: 200, textAlign: "center"}}>这是评论列表组件</h1>
{this.state.CommentList.map(item =>
<CmtItem {...item} key={item.id}/>
)}
</div>
}
}
结果如下: