组件&props
组件,概念上是类似于JS内的函数,接受任意入参(props),并返回页面用于展示的react元素。
函数组件
使用函数定义一个组件,称为功能组件,也称为无状态组件,只用于渲染。
显示传参,参数通过props.xxx 对象获取。
函数组件可以通过hook添加钩子,对函数组件进行状态改变
function hello(props){
return (
<div>
<h1> hello </h1>
</div>
)
}
//hook 内的useState
const [count,setCount] = useState(1)
const [arr,setArr] = useState([
{name:'1'},
{name:'2'}
])
function addArr(){
let newObj={name:'3'}
setArr([...arr,newObj]}
}
function hello(props){
return (
<div>
<h1> hello </h1>
<button onClick={addArr}>添加数据 </button>
<button onClick={()=>setCount(count+1)}>加法 </button> //每次点击 count+1
</div>
)
}
Class组件
使用es6 class来定义一个组件,成为类组件或状态组件,也叫做容器组件。
隐式传参,参数通过this.props.xx 对象获取
当前的this指向,指向calss组件本身
class hello extends React.Component{
render(){
return(
<div>
<h1> hello </h1>
</div>
)
}
}
State
不同于props,state可以被修改,state主要作用是组件用于保存、控制和修改自己的状态,它只能在constructor中初始化,它算是组件的私有属性,不可以通过外部访问和修改
当我们调用this.setState方法时,React会更新组件的数据状态state,并重新调用render()方法,对组件重新渲染。
class Demo extends React.component{
constructor(){
//该函数用于继承父类的实例和方法,必写
super()
this.state{
}
}
}
State的更新可能式异步的
//this.props和this.state可能会异步更新,不要依赖他们的值来更新下一个状态
this.setState({
conter:this.state.couter+this.props.num
})
//要解决这个问题的话,可以让setState()接收一个函数而不是一个对象,这个函数用上一个state作为第一
//个参数,将此次更新被应用时的props作为第二个参数
this.setState((state,props) => ({
conter :state.conter+props.num
}))
事件处理
在JS中,Class方法默认不会绑定this,当事件声明调用的是函数声明而非箭头函数时,这个this为undefined,举例:
class Hello extends React.component{
constructor(){
super()
this.state = {
turn:false
}
//方法二,改变this指向
this.isClick = this.showTwo.bind(this)
}
//方法一
shows() {
console.log(this)
// this指向undefined
this.setState({turn:true})
}
//方法二
showTwo() {
console.log(this)
//可以打印this
this.setState({turn:true})
}
//方法三
showThree() {
console.log(this)
//可以打印this
this.setState({turn:true})
}
//方法四
showFour = () => {
console.log(this)
//可以打印this
this.setState({turn:true})
}
render(){
<div>
//方法一,不生效
<button onClick ={this.shows()}> 按钮1</button>
//方法二,生效
<button onClick ={this.isClick}> 按钮2</button>
//方法三,生效
<button onClick ={this.showThree.bind(this)}> 按钮3</button>
//方法四,常用,生效 因为箭头函数没有自己的this指向。
<button onClick ={()=> this.showFour()}> 按钮3</button>
</div>
}
}
事件参数传递
//箭头函数,显示传递
<button onClikc ={ ()=> this.isClick('xiaoMing','18',e) }>
isClick = (name,age,e) => {
console.log(name) //'xiaoMing'
console.log(age) // 18
console.log(e) // event
}
//bind改变指向,隐式传递
<button onClikc ={ ()=> this.isClick.bind(this,'xiaoMing','18') }>
//有趣的事情来了,打印参数会发现不同,第一个参数打印出来并不是this
//参数C打印的也不是age,而是event事件
isClick = (a,b,c) => {
console.log(a) //'xiaoMing'
console.log(b) // 18
console.log(c) // event
}