案例:評論列表組件
下面演示使用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>
}
}
結果如下: