vscode默认组件的模板快捷键:rcc类组件,rfc
User.js
import React,{Component}from'react';
class User extends Component{
/**
*
* 类组件的props是存储在我们的实例对象中,可以直接访问
* this.props
*
* 类组件中我们的state统一存储到了实例对象的state属性中
* 可以通过this.state来访问
*/
//定义的时候不需要加this
//这里写一个count等价于在state里面加了个count属性
state={
count:0,
test:"hahah",
obj:{name:"顺悟空" ,age:18}
}
/**
* 改state里面的属性,通过this.setState()对齐进行修改
* 函数组件中,响应函数直接以函数的形式定义在组件中,
* 但是在类组件中只能定义方法,响应函数只能以类的方法来定义
*/
clickHandler=()=>{
/*
解决异步的问题应该这么写
this.setState(prevState=>{
return{
count:prevState.count+1
}
});
*/
this.setState({count:this.state.count+1});
//只修改count我们的test会不会丢???
//不会丢属性!!!!只会修改设置的属性
//为什么不会丢??因为我们这个东西是直接存储在state中
//那么我们要是在里面存储一个结构体,里面两个属性,只
//修改其中一个的话会不会丢另一个??
//会的!!!,因为这个对象并不是直接存在state中,而是存在于state的属性里
//正确写法
this.setState({
obj:{...this.state.obj,name:"沙和尚"}
})
};
//获取dom对象
//1.创建一个属性,用来存储dom对象
divRef=React.createRef();
//2.将这个属性设置为元素的ref值,react就会自动传
render(){
return (
<div ref={this.divRef}>
<h1>{this.state.count}</h1>
<button onClick={this.clickHandler}>点</button>
<ul>
<li> 姓名:{this.props.name}</li>
<li>性别:{this.props.age}</li>
<li>年龄:{this.props.gender}</li>
</ul>
</div>
);
}
}
export default User;
注意:为了省事,在类组件中响应函数都应该以箭头函数的形式定义。如果用普通函数我们把参数传过去,this就变了,但是箭头函数可以把this绑定????
App.js
import './App.css';
import {Component} from "react";
import User from "./components/User.js";
class App extends Component{
render(){
return <div className="app">
<User name={'猪八戒'} age={28} gender={'男'}/>
</div>
}
}
export default App;