React三大核心属性

React三大核心属性:

1.state (存数据)

  • state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)

  • 组件被称为**“状态机”**, 通过更新组件的state来更新对应的页面显示(重新渲染组件)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>state简写方式</title>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>
	
	<!-- 引入react核心库 -->
	<script type="text/javascript" src="../js/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/react-dom.development.js"></script>
	<!-- 引入babel,用于将jsx转为js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<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>
			}

			//自定义方法————要用赋值语句的形式+箭头函数
			changeWeather = ()=>{
    
    
				const isHot = this.state.isHot
				this.setState({
    
    isHot:!isHot})
			}
		}
		//2.渲染组件到页面
		ReactDOM.render(<Weather/>,document.getElementById('test'))
				
	</script>
</body>
</html>
  • 组件中render方法中的this为组件实例对象 组件自定义的方法中this为undefined,如何解决?
  • 方法1:强制绑定this: 通过函数对象的bind()

  • 方法2:箭头函数

  • 注意:状态数据,不能直接修改或更新,必须使用setState进行修改

2.props(传递数据和方法)

  • 每个组件对象都会有props(properties的简写)属性

  • 组件标签的所有属性都保存在props中

  1. 内部读取某个属性值
this.props.name        
  1. 对props中的属性值进行类型限制和必要性限制

使用prop-types库进限制(需要引入prop-types库)

 Person.propTypes = {      
 	name: PropTypes.string.isRequired,      
 	age: PropTypes.number.      
 }      
  1. 扩展属性: 将对象的所有属性通过props传递
 <Person {...person}/>        
  1. 默认属性值:
Person.defaultProps = {      
	age: 18,      
	sex:'男'     
}             
  1. 组件类的构造函数
 constructor(props){      
	 super(props)      
 	 console.log(props)//打印所有属性    
 }     

3.refs(获取DOM节点的属性)

组件内的标签可以定义ref属性来标识自己
推荐方法 回调形式的ref

 <input ref={
    
    (c)=>{
    
    this.input1 = c}}/>  
<script type="text/babel">
		//创建组件
		class Demo extends React.Component{
    
    
			//展示左侧输入框的数据
			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>
				)
			}
		}
		//渲染组件到页面
		ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
	</script>

猜你喜欢

转载自blog.csdn.net/z2000ky/article/details/129069470