1、获取ref
- 在你要获取的
dom
上添加ref
属性
ref={ (dom) => { this.[自定义名字] = dom } }
- 通过
this.[自定义名字]
来调用 Test.js
—— 点击 Test 能打印出 div 这个DOM节点
import React, {Component, Fragment} from 'react'
class Test extends Component {
constructor(props){
super(props)
this.show = this.show.bind(this)
}
render(){
return (
<Fragment>
<div
ref={ (dom) => { this.div = dom } }
onClick={this.show}
>Test</div>
</Fragment>
)
}
show(){
console.log( this.div )
}
}
export default Test
2、setState 中使用 ref
- 因为 setState 是异步函数,有时候想要 setState 后再调用 DOM 的话会出错,如以下情况
- 点击后,把 data 的内容改变,并打印出最新的文本内容
- 但因为 setState 是异步函数的关系,导致打印出来的依旧是 Test
import React, {Component, Fragment} from 'react'
class Test extends Component {
constructor(props){
super(props)
this.state = {
data: 'Test'
}
this.change = this.change.bind(this)
}
render(){
return (
<Fragment>
<div
ref={ (dom) => { this.div = dom } }
onClick={this.change}
>{this.state.data}</div>
</Fragment>
)
}
change(){
this.setState( (prevState) => ({data: 'hello'}))
console.log( this.div.innerHTML )
}
}
export default Test
- 这时候,只需要往 setState 中传第二个参数——回调函数,这样就会在setState完成后再打印
change(){
this.setState( (prevState) => ({data: 'hello'}), () => {
console.log( this.div.innerHTML )
})
}