执行结果如下
<!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