執行結果如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</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>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
//react推薦使用內聯樣式
var myStyle = {
fontSize: 30,
fontFamily: 'Monospace',
color: '#FF0000'
};
var arr = [
<h1> JSX允許在模板中插入數組 </h1>,
<h2> 數組會自動展開所有成員 </h2>,
<h2> 就像這樣 </h2>
]
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
/* 將生命週期方法添加到類中*/
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello,World!</h1>
{/*爲什麼要加this.props?*/}
<h2>Now: {this.state.date.toLocaleString()}</h2>
</div>
);
}
}//這樣就封裝了一個組件
class MyStyle extends React.Component {
render() {
return <h1 style={myStyle}>This is myStyle.</h1>;
}
}
class MyArray extends React.Component {
render() {
return <div> {arr} </div>
}
}
function App(props) {
return (
<div>
<Clock />
<MyStyle myStyle={myStyle} />
<MyArray arr={arr} />
</div>
)
}
const element = <App />
ReactDOM.render(
element,
document.getElementById('example')
);
</script>
</body>
</html>
執行順序:
效果:(不會截gif圖)
關於setState可參考:https://segmentfault.com/a/1190000015463599?utm_source=tag-newest
本文參考:
https://www.runoob.com/react/react-state.html