学习目标
React是啥?
官方定义:将前端请求获取到的数据渲染为HTML视图的JavaScript库。
直接创建react,使用初始化会创建package.json
npm init -y
再安装
使用纯JS创建ReactDOM(元素)
- <body>
- <div id="root">div>
- <script src="./node_modules/react/umd/react.development.js">script>
- <script src="./node_modules/react-dom/umd/react-dom.development.js">script>
- <script>
- // 2、使用JS创建react元素----虚拟DOM
- // 参数:元素名称、元素属性、元素子节点
- const title = React.createElement('h1',null,'Hello react 我是你大爷')
- // 3、渲染react元素
- // 参数:要渲染的react元素、挂载点
- ReactDOM.render(title,document.getElementById('root'))
- script>
-
- body>
React.createElement()方法使用不是很灵活,知道就好;
ReactDOM.render()方法渲染react元素很重要!!!使用起来友好。
使用react脚手架初始化项目,避免了使用
实现组件通信方法 -- 定义为父子组件
将父组件的state作为子组件的props,当父组件的state改变,子组件的props也跟着改变,其实它仍旧遵循了这一定律:props是不可更改的。
子组件调用父组件的方法
(1)子组件要拿到父组件的属性,需要通过 this.props
方法。
(2)同样地,如果子组件想要调用父组件的方法,只需父组件把要被调用的方法以属性的方式放在子组件上, 子组件内部便可以通过“this.props.被调用的方法
”这样的方式来获取父组件传过来的方法。
父组件传参数、函数,子组件接收实例
- import React, { Component, Fragment } from "react";
- //React的props传参
- // 父组件
- class App extends Component {
- render() {
- return (
- <Fragment>
- <Child name="卡卡罗特" jineng={this.bianshen}>Child>
- Fragment>
- );
- }
-
- bianshen() {
- return "变身超级赛亚人";
- }
- }
- // 子组件
- class Child extends Component {
- render() {
- return (
- <div>
- {this.props.name}
- {this.props.jineng()}
- div>
- );
- }
- }
-
- export default App;
父组件调用子组件的方法 在 ReactJS 中有个叫 ref 的属性。这个属性就像给组件起个引用名字一样,子组件被设置为 ref 之后(比如 ref=“xxx”)。父组件便可以通过 this.refs.xxx
来获取到子组件了。
组件内的标签定义ref标识自己
字符串形式 -- 简单好用但逐渐过时
回调形式 -- 麻烦
createRef -- 官方最新
将发生的事件作为参数
- class Demo extends React.Component{
- // React.createRef调用后返回一个容器 可存储被ref标识的节点 但只能一个
- myRef = React.createRef()
- myRef2 = React.createRef()
- // 展示左侧输入框的数据
- showData = ()=>{
- alert(this.myRef.current.value)
- }
-
- // 展示右侧输入框的数据
- showData2 = (event)=>{
- alert(event.target.value)
- }
- render(){
- return(
- <div>
- <input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
- <button onClick={this.showData}>点我提示左侧的数据button>
- {/*发生事件的元素刚好是要操作的元素,就可省略ref*/}
- <input onBlur={this.showData2} type="text" placeholder="点击按钮提示数据"/>
- div>
- )
- }
- // 事件处理中,点击第二个输入文本就是一个未指定的事件,在showData2函数中将点击事件作为参数获取值显示
- }
- ReactDOM.render(<Demo/>,document.getElementById("test1"))
旧版本
组件的钩子中只有三个钩子常用
1、初始化阶段:由ReactDOM.render()出发 -- 初次渲染
1、constructor()
2、componentWillMount()
3、render()
4、componentDidMount() ====》常用
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
2、更新阶段:有组件内部this.setState()或父组件render触发
1、componentWillReceiveProps()
2、shouldComponentUpdate()
3、componentWillUpdate()
4、render() 必用
5、componentDidUpdate()
3、卸载阶段:由ReactDOM.unmountComponentAtNode()触发
1、componentWillUnmount() ===》常用
一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息
基本钩子实例
-