一.脚手架的安装
1.全局安装脚手架
npm install create-react-app -g
2.初始化项目
在根目录中打开命令提示符
create-react-app 项目名称
3.运行
cd 项目名称
npm start
二.项目目录结构
1.node_modules 项目依赖文件
2.public 项目资源目录,里面包含首页、静态资源
index.html 项目首页
3.src 项目主目录
index.js 项目启动程序
App.js 项目根组件
4. .gitignore git 版本库忽略文件
5.package.json 项目依赖配置文件
三.组件
1.注意点
(1){}中的内容为JavaScript语法,()里面的内容为html语法
2.函数式组件
import React from "react"function Home(){ return( <h2>这是函数式组件</h2> )}export default Home;
3.类文件式组件
import React, { Component } from "react"import News from "./New"var title = "走自己选择的路,成为自己期盼的人"var target = "成为有钱,有思想的人"export default class HomeOne extends Component { constructor() { super() } render() { return ( <div> <h3>这是类名组件</h3> <News title={title} target={target}></News> </div> ) }}
4.函数式组件的父子传值(声明变量赋值+子组件自定义属性)
(1)在父组件中
import React, { Component } from "react"import News from "./New"var title = "走自己选择的路,成为自己期盼的人"var target = "成为有钱,有思想的人"export default class HomeOne extends Component { constructor() { super() } render() { return ( <div> <h3>这是类名组件</h3> <News title={title} target={target}></News> </div> ) }}
(2)在子组件中
import React from "react"function MyNews(props) { return ( <div> <p>原则:{props.title}</p> <p>目标:{props.target}</p> </div> )}export default MyNews
5.类文件格式组件的父子传值(声明变量提升+子组件使用状态机的props)
父组件中
import React,{Component} from "react"import Zi from "./zi"export default class MyFu extends Component{ constructor(){ super(); this.state = { msg:"哈哈哈" } } render(){ return( <div> <h1>这是父组件</h1> <Zi str={this.state.msg}></Zi> </div> ) }}
子组件中
import React, { Component } from "react"export default class MyZi extends Component { render() { console.log(this) return ( <div> <h1>来自父组件的数据:{this.props.str}</h1> </div> ) }}
6.状态机
在react中默认有设置类组件初始值的属性,叫做state。在页面加载完成后可以在state中定义一些初始数据。state中的数据如果需要进行改变,并且让页面及时的更新,需要调用setStat函数。
例如:实现类似vue的双向绑定
import React,{ Component } from "react"export default class extends Component{ constructor(){ super(); this.state = { msg:"" } } change(e){ console.log(e) this.setState({ msg : e.target.value }) } render(){ return( <div> <input type="text" value={this.content} onChange={(e)=>this.change(e)}></input> <h2>{this.state.msg}</h2> </div> ) }}