-
项目中使用React中的方法:
- 1.SCRIPT标签直接引入
在 </body>
结束标签之前,向 HTML 页面中添加三个 <script>
标签:
<!-- 注意: 部署时,将 "development.js" 替换为 "production.min.js"。-->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- 加载 React 组件。-->
<script src="like_button.js"></script>
</body>
- 2.使用脚手架来生成一个完整得react项目构架、
前提提要:下载全局脚手架工具
①前提: Node.js > 8.10 ②下载全局脚手架工具 npm i -g create-react-app
npx create-react-app 项目名
cd 项目名
npm start //启动项目
注意: npx
不是拼写错误 —— 它是npm 附带得package运行工具 。
项目启动后 点击生成网址可直接本地测试(生成得项目结构如图所示)
-
开启React之旅
- 在页面渲染一个标签元素Hello react
可以将生成得App.js文件后缀改成App.jsx,这样软件可自动加载标签更加方便。
1.我们先在App.jsx中渲染一个简单得标签,代码如下
2.也可在src目录下自建一个.jsx文件(本次示例Hello.jsx)
并在App.jsx文件中引用Hello.jsx
这样浏览器页面中就会渲染出元素 Hello React
2.组件和props
组件的定义可分为2种
- 函数声明组件
- 类声明组件
①函数组件
函数就是组件
组件名称规定首字母大写,小写认为是一个标签元素
组件在元素中应用<组件名/> or <组件名></组件名>
组件传递的属性或方法(<组件名 name="Sara" />)会把传入的属性包成一个对象({name="Sara"})传给这个组件函数props,在组件内取值时就是,{props.name}
函数组件会在内部添加一个render方法,把函数的返回结果作为render方法的返回结果
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
- 函数组件的不足
没有状态 新版本有增加
没有生命周期的钩子 新版本有增加
函数组件中没有this
- 类组件
类组件在渲染时会默认调用render方法
import React from "react";
import ReactDOM from "react-dom";
class Clcok extends React.Component{
render(){
return <h1>Hello React</h1>
}
}
- 类组件内有状态和钩子函数
- 需要继承React.Component
- React.Component 是一个基类,有生命周期,更改状态的方法
- 继承React.Component 之后才算是一个React类。
import React from "react";
import ReactDOM from "react-dom";
class Hello extends React.Component{
constructor(props){ //接收组件传入的属性or方法
super(props);
this.state={ } //this.state 表示给这个组件生命状态
}
render(){
return <h1>Hello</h1>
}
}
3.State & 生命周期
- React 的数据源(props(外部传入,不可修改) ,state(内部自带,可修改))
props 会把组件传入的属性or方法放在this上 ---- 取值时:this.props.name1
this.state 状态 ---- 取值时:this.state.name1
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
- this.setState
是父类提供的,用于修改状态,这种更新状态的方式,不会覆盖之前的,只会进行比较把更新的状态进行合并
this.setState 会刷新页面,如果不用this.setState。直接修改state 会改状态还是页面不会刷新
需要改属性的话只能把属性(props)变为状态(state)
- React 生命周期(钩子函数)
- componentDidMount(){} 当前组件挂在完成,在render方法加载完之后执行
- unmountComponentAtNode() 卸载组件
//用法
ReactDOM.unmountComponentAtNode(window.root)
- componentWillUnmount(){} 将要卸载,在此阶段中删掉所有的监听和卸载异步方法
componentDidMount(){
this.itemer = setInterval=()=>{
//this.setState 可以导致页面刷新
this.setState({time:new Date().toLocalString()})
}
}
componetWillUnmount(){
clearInterval(this.timer);
}