【React】React学习笔记二:React面向组件开发

学习视频链接

一、React中定义组件

1.函数式组件(适用于[简单组件])

  • 组件首字母必须大写
  • 函数必须有返回值
  • render的第一个参数是组件标签,不能直接写组件名字
//1.创建函数式组件
function MyComponent(){
	console.log(this); //此处的this是undefined,因为babel编译后开启了严格模式
	return <h2>我是用函数定义的组件(适用于【简单组件】的定义)</h2>
}
//2.渲染组件到页面
ReactDOM.render(<MyComponent/>,document.getElementById('test'))

执行了ReactDOM.render(<MyComponent/>.......之后,发生了什么?

  1. React解析组件标签,找到了MyComponent组件。
  2. 发现组件是使用函数定义的,随后调用该函数将返回的虚拟DOM转为真实DOM,随后呈现在页面中。

2.类式组件(适用于[复杂组件])

  • 必须基础React.Component父类
  • 必须有render
  • render必须有返回值
//1.创建类式组件
class MyComponent extends React.Component {
	render(){
		//render是放在哪里的?—— MyComponent的原型对象上,供实例使用。
		//render中的this是谁?—— MyComponent的实例对象 <=> MyComponent组件实例对象。
		console.log('render中的this:',this);
		return <h2>我是用类定义的组件(适用于【复杂组件】的定义)</h2>
	}
}
//2.渲染组件到页面
ReactDOM.render(<MyComponent/>,document.getElementById('test'))

执行了ReactDOM.render(<MyComponent/>.......之后,发生了什么?

  1. React解析组件标签,找到了MyComponent组件。
  2. 发现组件是使用类定义的,随后new出来该类的实例,并通过该实例调用到原型上的render方法。
  3. 将render返回的虚拟DOM转为真实DOM,随后呈现在页面中。

注意:

  1. 组件名必须首字母大写
  2. 虚拟DOM元素只能有一个根元素
  3. 虚拟DOM元素必须有结束标签

二、组件实例三大属性:state

复杂组件有状态,简单组件无状态

1.理解

  1. state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)
  2. 组件被称为"状态机", 通过更新组件的state来更新对应的页面显示(重新渲染组件)

2.注意

  1. 组件中render方法中的this为组件实例对象
  2. 组件自定义的方法中this为undefined,如何解决?
    a) 强制绑定this: 通过函数对象的bind()
    b) 箭头函数
  3. 状态数据,不能直接修改或更新,必须通过setState进行更新

3.例子

(1)state的使用

构造器中先初始化state(对象形式)

constructor(props){
	super(props)
	//初始化状态
	this.state = {isHot:false,wind:'微风'}
}

在render中通过三目表达式,判断是否显示炎热

render(){
	//读取状态
	const {isHot,wind} = this.state
	return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
}

(2)事件绑定的写法

首先定义点击事件

render(){
	const {isHot,wind} = this.state
	return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
}	

在类中定义事件处理函数,如果事件发生,则通过setState修改状态

changeWeather(){
	//获取原来的isHot值
	const isHot = this.state.isHot
	//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
	this.setState({isHot:!isHot})
	//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
	//this.state.isHot = !isHot //这是错误的写法
}

但是,由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用。而类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined

解决changeWeather中this指向问题,强制绑定this

constructor(props){
	//解决changeWeather中this指向问题
	this.changeWeather = this.changeWeather.bind(this)
}

4.简写方式

  • 去掉构造器
  • 自定义方法————要用赋值语句的形式+箭头函数
class Weather extends React.Component{
	//初始化状态
	state = {isHot:false,wind:'微风'}

	render(){
		const {isHot,wind} = this.state
		return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
	}

	//自定义方法————要用赋值语句的形式+箭头函数
	changeWeather = ()=>{
		const isHot = this.state.isHot
		this.setState({isHot:!isHot})
	}
}
//2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))

三、组件实例三大属性:props

1.理解

  • 每个组件对象都会有props(properties的简写)属性
  • 组件标签的所有属性都保存在props中

2.作用

  • 通过标签属性从组件外向组件内传递变化的数据
  • 注意: 组件内部不要修改props数据

3.基本使用

创建组件

class Person extends React.Component{
	render(){
		// console.log(this);
		const {name,age,sex} = this.props
		//props是只读的
		//this.props.name = 'jack' //此行代码会报错,因为props是只读的
		return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age+1}</li>
			</ul>
		)
	}
}

对标签属性进行类型、必要性的限制

Person.propTypes = {
	name:PropTypes.string.isRequired, //限制name必传,且为字符串
	sex:PropTypes.string,//限制sex为字符串
	age:PropTypes.number,//限制age为数值
	speak:PropTypes.func,//限制speak为函数
}

指定默认标签属性值

Person.defaultProps = {
	sex:'男',//sex默认值为男
	age:18 //age默认值为18
}

定义speak函数

function speak(){
	console.log('我说话了');
}

渲染组件到页面

ReactDOM.render(<Person name={100} speak={speak}/>,document.getElementById('test1'))
ReactDOM.render(<Person name="tom" age={18} sex="女"/>,document.getElementById('test2'))

const p = {name:'老刘',age:18,sex:'女'}
// console.log('@',...p);
// ReactDOM.render(<Person name={p.name} age={p.age} sex={p.sex}/>,document.getElementById('test3'))
ReactDOM.render(<Person {...p}/>,document.getElementById('test3'))

4.简写

//创建组件
class Person extends React.Component{

	constructor(props){
		//构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
		// console.log(props);
		super(props)
		console.log('constructor',this.props);
	}

	//对标签属性进行类型、必要性的限制
	static propTypes = {
		name:PropTypes.string.isRequired, //限制name必传,且为字符串
		sex:PropTypes.string,//限制sex为字符串
		age:PropTypes.number,//限制age为数值
	}

	//指定默认标签属性值
	static defaultProps = {
		sex:'男',//sex默认值为男
		age:18 //age默认值为18
	}
	
	render(){
		// console.log(this);
		const {name,age,sex} = this.props
		//props是只读的
		//this.props.name = 'jack' //此行代码会报错,因为props是只读的
		return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age+1}</li>
			</ul>
		)
	}
}

//渲染组件到页面
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))

5.函数组件使用props

函数式组件不能使用state和ref,但可以用props

//创建组件
function Person (props){
	const {name,age,sex} = props
	return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age}</li>
			</ul>
		)
}
Person.propTypes = {
	name:PropTypes.string.isRequired, //限制name必传,且为字符串
	sex:PropTypes.string,//限制sex为字符串
	age:PropTypes.number,//限制age为数值
}

//指定默认标签属性值
Person.defaultProps = {
	sex:'男',//sex默认值为男
	age:18 //age默认值为18
}
//渲染组件到页面
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))

四、组件实例三大属性:refs

1.理解

组件内的标签可以定义ref属性来标识自己。

2.字符串形式的ref

(过时了)

//展示左侧输入框的数据
showData = ()=>{
	const {input1} = this.refs
	alert(input1.value)
}
//展示右侧输入框的数据
showData2 = ()=>{
	const {input2} = this.refs
	alert(input2.value)
}
render(){
	return(
		<div>
			<input ref="input1" type="text" placeholder="点击按钮提示数据"/>&nbsp;
			<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			<input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"/>
		</div>
	)
}

3.回调函数形式的ref

把ref所在的这个节点挂在了组件自身上

//展示左侧输入框的数据
showData = ()=>{
	const {input1} = this
	alert(input1.value)
}
//展示右侧输入框的数据
showData2 = ()=>{
	const {input2} = this
	alert(input2.value)
}
render(){
	return(
		<div>
			<input ref={c => this.input1 = c } type="text" placeholder="点击按钮提示数据"/>&nbsp;
			<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			<input onBlur={this.showData2} ref={c => this.input2 = c } type="text" placeholder="失去焦点提示数据"/>&nbsp;
		</div>
	)
}

4.createRef的使用

React.createRef调用后可以返回一个容器,该容器可以存储被ref所标识的节点。

myRef = React.createRef()
myRef2 = React.createRef()
//展示左侧输入框的数据
showData = ()=>{
	alert(this.myRef.current.value);
}
//展示右侧输入框的数据
showData2 = ()=>{
	alert(this.myRef2.current.value);
}
render(){
	return(
		<div>
			<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>&nbsp;
			<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			<input onBlur={this.showData2} ref={this.myRef2} type="text" placeholder="失去焦点提示数据"/>&nbsp;
		</div>
	)
}

五、React中事件处理

1.两种方式处理

(1) onXxx属性指定事件处理函数
通过onXxx属性指定事件处理函数(注意大小写)

  • a. React使用的是自定义(合成)事件, 而不是使用的原生DOM事件—— 为了更好的兼容性
  • b. React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) ——为了的高效

(2) event.target——不要过度使用ref
发生事件的元素正好是要操作的元素,通过event.target得到发生事件的DOM元素对象

2.案例

//创建ref容器
myRef = React.createRef()
myRef2 = React.createRef()

//展示左侧输入框的数据
showData = (event)=>{
	console.log(event.target);
	alert(this.myRef.current.value);
}

//展示右侧输入框的数据
showData2 = (event)=>{
	alert(event.target.value);
}

render(){
	return(
		<div>
			<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>&nbsp;
			<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			<input onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"/>&nbsp;
		</div>
	)
}

六、React中收集表单数据

  • 非受控组件:有几个输入项,就有几个ref
  • 受控组件:不适应ref

1.非受控组件

现用现取

class Login extends React.Component{
	handleSubmit = (event)=>{
		event.preventDefault() //阻止表单提交
		const {username,password} = this
		alert(`你输入的用户名是:${username.value},你输入的密码是:${password.value}`)
	}
	render(){
		return(
			<form onSubmit={this.handleSubmit}>
				用户名:<input ref={c => this.username = c} type="text" name="username"/>
				密码:<input ref={c => this.password = c} type="password" name="password"/>
				<button>登录</button>
			</form>
		)
	}
}

2.受控组件

//初始化状态
state = {
	username:'', //用户名
	password:'' //密码
}

//保存用户名到状态中
saveUsername = (event)=>{
	this.setState({username:event.target.value})
}

//保存密码到状态中
savePassword = (event)=>{
	this.setState({password:event.target.value})
}

//表单提交的回调
handleSubmit = (event)=>{
	event.preventDefault() //阻止表单提交
	const {username,password} = this.state
	alert(`你输入的用户名是:${username},你输入的密码是:${password}`)
}

render(){
	return(
		<form onSubmit={this.handleSubmit}>
			用户名:<input onChange={this.saveUsername} type="text" name="username"/>
			密码:<input onChange={this.savePassword} type="password" name="password"/>
			<button>登录</button>
		</form>
	)
}

五、高阶函数-函数柯里化

1.概念

(1)高阶函数:如果一个函数符合下面2个规范中的任何一个,那该函数就是高阶函数。常见的高阶函数有:Promise、setTimeout、arr.map()等等。

  • 若A函数,接收的参数是一个函数,那么A就可以称之为高阶函数。
  • 若A函数,调用的返回值依然是一个函数,那么A就可以称之为高阶函数。

(2)函数的柯里化:通过函数调用继续返回函数的方式,实现多次接收参数最后统一处理的函数编码形式。

function sum(a){
	return(b)=>{
		return (c)=>{
			return a+b+c
		}
	}
}

2.例子

//初始化状态
state = {
	username:'', //用户名
	password:'' //密码
}

//保存表单数据到状态中
saveFormData = (dataType)=>{
	return (event)=>{
		this.setState({[dataType]:event.target.value})
	}
}

//表单提交的回调
handleSubmit = (event)=>{
	event.preventDefault() //阻止表单提交
	const {username,password} = this.state
	alert(`你输入的用户名是:${username},你输入的密码是:${password}`)
}
render(){
	return(
		<form onSubmit={this.handleSubmit}>
			用户名:<input onChange={this.saveFormData('username')} type="text" name="username"/>
			密码:<input onChange={this.saveFormData('password')} type="password" name="password"/>
			<button>登录</button>
		</form>
	)
}

六、组件的生命周期

1.旧生命周期

在这里插入图片描述

1.初始化阶段: 由ReactDOM.render()触发——初次渲染

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()

2.更新阶段: 由组件内部this.setSate()或父组件重新render触发

  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

3.卸载组件: 由ReactDOM.unmountComponentAtNode()触发

  • componentWillUnmount()

2.新生命周期

在这里插入图片描述

1.初始化阶段: 由ReactDOM.render()触发—初次渲染

  • constructor()
  • getDerivedStateFromProps
  • render()
  • componentDidMount()

2.更新阶段: 由组件内部this.setSate()或父组件重新render触发

  • getDerivedStateFromProps
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate
  • componentDidUpdate()

3.卸载组件: 由ReactDOM.unmountComponentAtNode()触发

  • componentWillUnmount()

3.重要的勾子

  • render:必须的,初始化渲染或更新渲染调用
  • componentDidMount:页面一上来就做的初始化操作(例如:订阅消息,开启监听, 发送网络请求)
  • componentWillUnmount:做一些收尾工作, 如: 清理定时器,取消订阅消息

七、DOM的Diffing算法

1.react/vue中的key有什么作用?

虚拟DOM中key的作用: key是虚拟DOM对象的标识, 在更新显示时key起着极其重要的作用。详细的说: 当状态中的数据发生变化时,react会根据【新数据】生成【新的虚拟DOM】, 随后React进行【新虚拟DOM】与【旧虚拟DOM】的diff比较。

比较规则如下:

  • a. 旧虚拟DOM中找到了与新虚拟DOM相同的key,若虚拟DOM中内容变了, 则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
  • b. 旧虚拟DOM中未找到与新虚拟DOM相同的key,根据数据创建新的真实DOM,随后渲染到到页面

八、todoList案例总结

1.拆分组件、实现静态组件,注意:className、style的写法

2.动态初始化列表,如何确定将数据放在哪个组件的state中?
        - 某个组件使用:放在其自身的state中
        - 某些组件使用:放在他们共同的父组件state中(官方称此操作为:状态提升)

3.关于父子之间通信
        - 【父组件】给【子组件】传递数据:通过props传递
        - 【子组件】给【父组件】传递数据:通过props传递,要求父提前给子传递一个函数(柯里化函数)

4.注意defaultChecked 和 checked的区别,类似的还有:defaultValue 和 value

5.状态在哪里,操作状态的方法就在哪里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值