12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <!-- jsx 语法浏览器不识别 jsx => js 浏览器可识别的语言 -->
- <script src="./babel.min.js"></script>
- <!-- react的核心库 -->
- <script src="./react.development.js"></script>
- <!-- 解析react中的dom库 -->
- <script src="./react-dom.development.js"></script>
- </head>
- <body>
- <div id="root"></div>
- <script type="text/babel">
- let root = ReactDOM.createRoot(document.getElementById("root"));
- function App() {
- return (
- <div>
- <h1>Hello, React!</h1>
- <Flower num={2} />
- </div>
- );
- }
- class Flower extends React.Component {
- constructor(props) {
- super(props);
- // props state 可以改变页面
- // props 只读 不修改
- // state 可修改
- this.state = {
- currentTime: new Date(),
- count: 0
- };
- }
- // 挂载
- componentDidMount() {
- console.log("挂载");
- console.log(this.props)
- this.timer = setInterval(() => {
- // currentTime: new Date()
- // 在react中 响应式更新状态 唯一方法:调用组件实例的setState方法
- // setState方法 在修改状态时候 就是新值 与 旧值合并后在覆盖掉旧状态
- // this.setState({
- // currentTime: new Date(),
- // // count: count + 1
- // })
- this.setState((state, props) => ({
- // console.log(state,props),
- currentTime: new Date(),
- count: state.count + 1 + props.num
- // counter: state.counter + props.increment,
- }));
- }, 1000);
- }
- // 更新
- componentDidUpdate() {
- console.log("更新");
-
- }
- // 卸载
- componentWillUnmount() {
- clearInterval(this.timer);
- }
- render() {
- // this.state.currentTime = 30;
- // console.log(this.state.count)
- return (
- <div>
- <h1>React</h1>
- <h3>{this.state.count}</h3>
- <p>当前时间:{this.state.currentTime.toLocaleString()}</p>
- </div>
- );
- }
- }
- root.render(<App />);
- </script>
- </body>
- </html>
|