基本使用
React提供的这个
ref
属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()
返回的组件实例,ref
可以挂载到组件上也可以是dom元素上。
- 挂到组件(
class
声明的组件)上的ref表示对组件实例的引用。不能在函数式组件上使用 ref 属性,因为它们没有实例 - 挂载到dom元素上时表示具体的dom元素节点
import React, { PureComponent } from 'react'
class Child extends PureComponent {
state = { aa: 100 }
fn = () => {
console.log(this.state.aa)
}
render () {
return (
<div>
Child
</div>
)
}
}
export default class App extends PureComponent {
testRef = React.createRef()
render() {
return (
<div>
<Child ref={ this.testRef }/>
</div>
)
}
componentDidMount () {
console.log(this.testRef.current.state.aa) // 100
this.testRef.current.fn() // 100
}
}
- 要使用
ref
, 需要使用React.createRef
方法先生成一个ref
。
import React ,{Component} from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor() {
super();
//创建一个ref对象
this.input = React.createRef();
}
submitForm = (ev) => {
//获取refs的值,this.refs.*** 已经淘汰了 用 useRef 或createRef来代替
console.log(this.input);
console.log("数据:", this.input.current.value);
ev.preventDefault();
}
render() {
return (<div>
<form onSubmit={this.submitForm}>
{/* 在非受控组件中不写value , defaultValue="李四 " 默认值*/}
用户名:<input type="text" name="username" ref={this.input} defaultValue="李四 " />
<input type="submit" value="提交" />
</form>
</div>);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
父子传值
父传值给子
父主动把数据给子,将
ref
对象绑定到子组件标签上,然后通过ref
对象获取整个子组件实例 ,随后可以在子组件调用一个方法,用于被ref
对象调用,来接收父组件的数据
import React, { Component, createRef } from "react";
class Farther extends Component {
// 构造函数
constructor(props){
super(props);
// 创建一个给子用的ref对象
this.child = createRef();
}
// 父的数据
state = {
msg:"父的数据"
}
render() {
return (
<div>
<Son ref={this.child}></Son>
{/* 方法一:父主动给子 */}
<p>点击按钮把数据发给子组件</p>
<button onClick={this.sendMsgToSon.bind(this)}>父传子</button>
</div>
);
}
// 主动把数据给子
sendMsgToSon(){
//
this.child.current.getMsgFromFather(this.state.msg);
}
}
// 子组件
class Son extends Component {
render() {
return (
<div>我是子组件</div>
);
}
// 接收父亲给的数据
getMsgFromFather(msg){
console.log("子收到的是:",msg);
}
}
export default Farther;
子传值给父
父主动向子要数据,给子组件绑定ref对象以获取整个子组件实例,也就是获取到了子组件的state,进而可以获取到state中的对象
import React, { Component, createRef } from "react";
class Farther extends Component {
// 构造函数
constructor(props){
super(props);
// 创建子组件的ref对象
this.child = createRef();
}
render() {
return (
<div>
<Son ref={this.child}></Son>
{/* 方法一:父主动去获取子的数据 */}
<button onClick={this.getMsgFromSon.bind(this)}>点击按钮把消息发给子组件</button>
</div>
);
}
// 父主动去获取子的数据
getMsgFromSon(){
console.log( this.child.current.state.msg);
}
}
// 子组件
class Son extends Component {
// 子的数据
state = {
msg:"子的数据"
}
render() {
return (
<div>这是子组件</div>
);
}
}
export default Farther;