import React, { PureComponent, createRef } from 'react'
export default class App extends PureComponent {
constructor(props) {
super(props)
this.titleRef2 = createRef()
this.titleRef3 = null
}
render() {
return (
<div>
<h2 ref="titleRef">code1</h2>
<h2 ref={this.titleRef2}>code2</h2>
<h2 ref={arg => this.titleRef3 =arg}>code3</h2>
<button onClick={() => this.change()}>改变文本</button>
</div>
)
}
change() {
// 1.字符串的方式
this.refs.titleRef.innerHTML = 'Hello React'
// 2.对象的方式(主流)
this.titleRef2.current.innerHTML = 'Hello JavaScript'
// 3.函数的方式
this.titleRef3.innerHTML = 'Hello Vue'
}
}
React ref 的使用
最新推荐文章于 2024-04-22 10:07:00 发布