react中ref 的用法
在react中的ref推荐使用以下这种方式,不在使用Vue里面的用法
首先引入方法
import { createRef } from "react";
然后再constructor里面定义这个Ref,下面创建了两个ref
例如
constructor() {
super();
this.testRef = createRef();
this.ageRef = createRef();
}
在子组件或者子元素进行绑定Ref的时候
render() {
return (
<div>
<p ref={this.testRef}>createRef获取</p> 分别绑定了两个不同的子元素p
<p ref={this.ageRef}>年龄 {this.state.age}</p>
);
}
在用的时候:
知识点:注意在用的时候后面要加上current
componentDidMount() {
console.log( this.testRef.current) //注意在用的时候后面要加上current
console.log(this.ageRef.current)
}
slot
在react里面并没有插槽,但是可以直接通过this.props.children来实现
例子:
在app.js
<Son1>
<p>
组件内部的内容
</p>
<h1>组件内部的内容</h1>
</Son1>
在son1.js
render() {
return (
<>
{/* {this.props.children[0]} */}
{this.props.children[0]}//相当于具名插槽,是p里面的内容
<h1> 这里是son1</h1>
{this.props.children}//直接写children就相当于匿名插槽
<p ref="p">1313</p>
{this.props.children[1]}//相当于具名插槽,是h1里面的内容
<RFor ref="rfor"></RFor>
</>
);
}