创建 refs 来获取对应的 DOM
-
传入字符串
<h2 ref="title">显示标题</h2>
console.log(this.refs.title)
2. 传入一个对象
import React from "react"
import ChildCpn from "./cpn.js"
class App extends React.Component {
constructor() {
super()
this.title = React.createRef()
}
handleClick = () => {
console.log(this.title.current) // <h2>显示标题</h2>
}
render() {
return (
<div>
<h2 ref={this.title}>显示标题</h2>
<button onClick={this.handleClick}>点击</button>
</div>
)
}
}
export default App
3.回调函数
import React from "react"
import ChildCpn from "./cpn.js"
class App extends React.Component {
constructor() {
super()
this.title = null
}
handleClick = () => {
console.log(this.title) // <h2>显示标题</h2>
}
render() {
return (
<div>
<h2 ref={(el) => { this.title = el }}>显示标题</h2> // 渲染之后,执行回调
<button onClick={this.handleClick}>点击</button>
</div>
)
}
}
export default App