为了加深一下记忆~写的博客
为以后能更好的维护,学习react项目,我初步认识了react,相信想接触react的小伙伴,都通过各个渠道了解一些了,不过为了能看懂代码我直接使用了 create react app ,它的官网create react app
下面是文件目录,我创建了一个components文件,测试组件用~

首先来看一眼组件代码,这里用注释介绍
import React, { Component } from "react"; //引入react
class Button extends Component { //es6 的clss类继承,我有空再写一篇博客来加深理解
//下面是基本的写法,class类中代码会是严格模式,就
import React, { Component } from "react";
class Button extends Component {
//es6 的clss类继承,我有空再写一篇博客来加深理解
//下面是基本的写法,class类中代码会是严格模式,就是说自定义的方法中,如果不适用箭头函数的话,this为undefind,所以我们如果在es6中,直接使用箭头函数替代function
constructor(props) {
//构造器,这里props是react必传,并且需要 super(),这里class继承的相关知识
super(props);
this.state = {
number: 0,
};
this.addNum = this.addNum.bind(this); //改变指向
}
addNum = function () {
this.setState({
number: this.state.number + 1,
});
};
// 这里是现在基本的通用写法
// state = {
// number: 0,
// };
// addNum = () => {
// this.setState({
// number: this.state.number + 1,
// });
// };
render() {
//render函数,里面是jsx语法,变量在{}里面
return <div onClick={this.addNum}> 点击我{this.state.number} </div>;
}
}
export default Button; // 别忘了使用 export default !
一个很简单的组件,主要是练习基本写法~然后引入app.js 里面使用
import React, { useState, useEffect } from "react"; //这里是hook 最基本的2个,其余的暂时还没有看~
import Button from "./components/botton"; //引入组件,请注意,组件开头必须为大写,不然无法渲染,具体想知道请百度~也算一种规范
import "./App.css";
function App() {
const [istitle, setTilte] = useState(true); //使用hook算是摒弃的this,直接使用useState,用数组结构来赋值
const [istitle2, setTilte2] = useState(true);
const click = () => {
setTilte(() => !istitle); //改变直接使用setTilte方法,参数可以照传
};
const click2 = () => {
setTilte2(() => !istitle2);
};
useEffect(() => { //useEffect,相当于监听了你后面数组所传数值的变化,然后调用事件,可以传多个
console.log("你点击了");
}, [istitle]); //只传istitle,就只会监听istitle的变化
return (
<div className="App">
<h1 onClick={click}>{istitle ? "hello,react" : "hello,change"}</h1>
<h1 onClick={click2}>{istitle2 ? "hello,react2" : "hello,change2"}</h1>
<Button /> {/*组件使用,这里注释这样写~~ */}
</div>
);
}
export default App;
先介绍这里~在慢慢学习
本文详细介绍React的基本用法,包括组件创建、状态管理及Hooks的使用。通过实例演示如何使用Create React App搭建项目,掌握class组件与函数组件的生命周期,以及如何通过state和props进行数据传递。
847

被折叠的 条评论
为什么被折叠?



