需要获取dom的时候使用 ,不建议多使用 因为会缓存到内存
- string类型绑定 (不推荐)
- 函数类型绑定 (不推荐)
- createRef绑定
ref获取DOM更改数据String绑定方式
import React from 'react'
export default class ChangeRef extends React.Component {
constructor(props) {
super(props)
this.state = {
title: 'ref数据'
}
}
render() {
return (
<div ref='box'>{this.state.title}
</div>
)
}
componentDidMount() {
this.refs.box.innerHTML = '更改refs数据'
}
}
ref回调函数式更改数据函数绑定方式
import React from 'react'
export default class ChangeRef extends React.Component {
constructor(props) {
super(props)
this.state = {
title: 'ref数据'
}
}
render() {
return (
<div ref={element => {
this.box2 = element
}}>{this.state.title}</div>
)
}
componentDidMount() {
this.box2.innerHTML = '更改refs数据'
}
}
createRef 专人专用,每次使用都要定义一个新的
class Demo extends React.Component{
constructor(props){
super(props)
this.container=React.createRef() //createRef 专人专用
this.container2=React.createRef()
}
aa(){
console.log(this.container.current.value)
}
bb(){
console.log(this.container2.current.value)
}
render(){
return (
<div>
<input type="text" ref={this.container} />
<button onClick={this.aa.bind(this)}>测试</button>
<input type="text" ref={this.container2} />
<button onClick={this.bb.bind(this)}>测试</button>
<Demo2/>
</div>
)
}
}