说明
- 本文通过ref 使其获得光标来进行展示
- 使用到了
componentDidMount()
方法: 在第一次渲染后调用,只在客户端- 用来执行代码,操作 ref
- ref 的名字统一命名为
content
- 使用 string 的方式直接绑定
- 这种方法以后会被废弃
<input type="text" ref="content"/> //绑定
this.refs.content.focus() //调用
代码展示:
<script type="text/babel">
class App extends React.Component {
componentDidMount(){
console.log(this.refs) //打印 ref 看看效果
this.refs.content.focus() //获取 ref --- this.refs.xxx
}
render(){
return (
<div>
<li>你好,这里是 li</li>
<input type="text" ref="content"/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
</script>
打印 ref 展示:
视图层结果展示:
- callback回调函数形式
- 推荐使用
- 就是将这个元素
ref
的名字绑定到this
里面,调用的时候直接this.xxx
<input type="text" ref={(el)=>this.content = el}/> //绑定
this.content.focus() //调用
代码展示:
<script type="text/babel">
class App extends React.Component {
componentDidMount(){
console.log(this.content)
this.content.focus()
}
render(){
return (
<div>
<li>你好,这里是 li</li>
<input type="text" ref={(el)=>this.content = el}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
</script>
打印 ref 展示:
视图层结果展示:
- createRef 形式(最新的方式)
- 推荐使用
- 通过
createRef
的形式进行ref
的元素绑定
this.content = React.createRef() //声明
<input type="text" ref={this.content}/> //绑定
this.content.current.focus() //调用
代码展示:
<script type="text/babel">
class App extends React.Component {
constructor(){
super()
this.content = React.createRef() //通过createRef的形式进行ref的元素绑定
}
componentDidMount(){
console.log(this.content)
this.content.current.focus() //第三步使用 //注意:通过current属性才可以获取到dom组件
}
render(){
return (
<div>
<li>你好,这里是 li</li>
{/*第二步:需要在使用的组件或者dom元素上通过ref指明*/}
<input type="text" ref={this.content}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
</script>
打印 ref 展示:
视图层结果展示: