2:React组件以及三大核心属性

模块:JS的拆分,一个JS负责一个功能
组件:html、css、js等一系列资源全都拆分,每一个组件可完成整体效果的一部分。提高程序的复用率,简化项目编码,提高程序运行率。

组件:

  • 函数式组件
  • 类式组件

函数式组件

function MyComponent(){
	console.log(this); //此处的this是undefined,因为babel编译后开启了严格模式,所以不是window
	return <h2>我是用函数定义的组件(适用于【简单组件:无状态】的定义)</h2>
}
//函数式组件需要首字母大写,babel在编译时才会发现这是组件,且使用时需要使用标签的形式
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
/* 
	执行了ReactDOM.render(<MyComponent/>.......之后,发生了什么?
	1.React解析组件标签,找到了MyComponent组件。
	2.发现组件是使用函数定义的,随后调用该函数,
	  将返回的虚拟DOM转为真实DOM,随后呈现在页面中。
*/

函数式组件使用props

<script type="text/javascript" src="../js/prop-types.js"></script>

	<script type="text/babel">
		//创建组件
		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'))
</script>

类式组件

<!--引入prop-types,才能使用propTypes中的PropTypes,需要限制props的类型才需要引入-->
<script type="text/babel">
	//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,随后呈现在页面中。
	*/
</script>

组件实例的三大核心属性

(只有类式组件才有,因为函数式组件中thisundefined,没有实例对象,但由于函数式组件中可以传递参数,故函数式组件中有props)

1:State

(深刻理解:)

  • changeWeather()thisundefined,render中要直接使用changeWeather()是不可以的,需借助构造器中的this.changeWeather = this.changeWeather.bind(this)
  • 状态必须通过setState进行更新,如this.setState({isHot:!isHot})
<script type="text/babel">
	//1.创建类组件,类组件才有staste这个属性
	class Weather extends React.Component{
		//构造器调用几次? ———— 1次
		constructor(props){
			console.log('constructor');
			super(props)
			//初始化状态
			this.state = {isHot:false,wind:'微风'}
			//解决changeWeather中this指向问题
			this.changeWeather = this.changeWeather.bind(this)
	}

	//render调用几次? ———— 1+n次 1是初始化的那次 n是状态更新的次数
	render(){
		console.log('render');
		//读取状态
		const {isHot,wind} = this.state
		return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
	}

	//changeWeather调用几次? ———— 点几次调几次
	changeWeather(){
		//changeWeather放在哪里? ———— Weather的原型对象上,供实例使用
		//由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
		//类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
		//获取原来的isHot值
		const isHot = this.state.isHot
		//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
		this.setState({isHot:!isHot})
		console.log(this);
		//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
		//this.state.isHot = !isHot //这是错误的写法
		}
	}
	//2.渲染组件到页面
	ReactDOM.render(<Weather/>,document.getElementById('test'))			
</script>

(简化书写)

  • 类式组件中可以直接书写 a=1这种形式的
  • 书写changeWeather,可以用赋值语句的形式+箭头函数,箭头函数中this没有含义,它找其外层的this
<script type="text/babel">
		//1.创建组件
		class Weather extends React.Component{
			//初始化状态
			state = {isHot:false,wind:'微风'}
	
			render(){
				const {isHot,wind} = this.state
				return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
			}

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

2:props

(复杂版)

  • 批量传递props...p
    注:原生JS中...p不能展开对象,需要let person2 = {...person}才可以,由于React中的react.development.jsbabel使得展开运算符...可以批量传递props,但仅仅只能用于传递props
  • 对props中标签的属性进行限制propTypes
  • 指定默认标签属性值defaultProps
<!--引入prop-types,才能使用propTypes中的PropTypes,需要限制props的类型才需要引入-->
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/babel">
		//创建组件
		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
		}
		//渲染组件到页面
		ReactDOM.render(<Person name={100} speak={speak}/>,document.getElementById('test1'))
		ReactDOM.render(<Person name="tom" age={18} sex="女"/>,document.getElementById('test2'))

		//批量传递props
		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'))

		function speak(){
			console.log('我说话了');
		}
</script>

(简化版):将propTypes、defaultProps变成static,放入类式组件中

<!--引入prop-types,才能使用propTypes中的PropTypes,需要限制props的类型才需要引入-->
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/babel">
		//创建组件
		class Person extends React.Component{
			//构造器方法大多数情况下都不写,没什么用
			constructor(props){
				//构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
				// console.log(props);
				super(props)
				console.log('constructor',this.props);
			}

			//对标签属性进行类型、必要性的限制
			static propTypes = {//小写p
				name:PropTypes.string.isRequired, //大写P,限制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'))
</script>

3:refs

  1. 字符串形式的ref(简单好用,但使用过多的ref效率不高,但目前的版本暂未移除)标签中的ref类似id的存在,将一系列标签中的一系列数据存放到实例对象的refs
<script type="text/babel">
		//创建组件
		class Demo extends React.Component{
			//展示左侧输入框的数据
			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>
				)
			}
		}
		//渲染组件到页面
		ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
</script>
  1. 回调形式的ref
  <script type="text/babel">
        class Demo extends React.Component{
            showData1 = ()=>{
                console.log(this)
                const {input1} = this
                alert(input1.value)
            }
            showData2 = ()=>{
                const {input2} = this
                alert(input2.value)
            }
            render(){
                return (
                    <div>
                    	//此处改变了,将当前节点放在了组件实例的自身上,命名为input1
                        <input ref={c => this.input1 = c} type="text" placeholder="点击按钮提示数据"/>&nbsp;
                        <button onClick={this.showData1}>点我提示左侧数据</button>&nbsp;
                        <input ref={c => this.input2 = c} onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"></input>
                    </div>
                )
            }
        }
        ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
  1. 回调refs中的一点小问题
    回调refs中的一点小问题
    改正后:转成赋值语句形式
<script type="text/babel">
        class Demo extends React.Component{
            showData1 = ()=>{
                console.log(this)
                const input1 = this
                alert(input1.value)
            }
            saveInput = (c)=>{
                this.input1 = c
                console.log('@',c)
            }
            render(){
                const  isHot = this.state.isHot
                return (
                    <div>
                        <div>今天天气很{isHot?  '炎热':'凉爽'}</div>
                        {/*JSX的注释方法  <input ref={c => {this.input1 = c;console.log('@',c)}} type="text" placeholder="点击按钮提示数据"/>&nbsp;*/}
                        <input ref={this.saveInput} type="text" placeholder="点击按钮提示数据"/>&nbsp;
                        <button onClick={this.showData1}>点我提示左侧数据</button>&nbsp;
                    </div>
                )
            }
        }
        ReactDOM.render(<Demo/>,document.getElementById('test'))
 </script>

但由于不影响执行效果,故一般采用的还是内联样式的ref

  1. createRefs API形式的ref
	<script type="text/babel">
		//创建组件
		class Demo extends React.Component{
			/* 
				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>
				)
			}
		}
		//渲染组件到页面
		ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值