1.字符串形式的ref
class Demo extends React.Component {
// 自定义函数要用箭头函数,才能拿到正确的this
showDlg = () => {
const input = this.refs.input1
alert(input.value)
}
showDlg2 = () => {
const input = this.refs.input2
alert(input.value)
}
render() {
return (
<div>
<input ref="input1" type="text" placeholder="点击按钮弹出内容" />
<button onClick={this.showDlg}>点击弹出内容</button>
<input ref="input2" type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
</div>
)
}
}
ReactDOM.render(<Demo />, document.getElementById('test1'))
笔记:
- 定义:ref=“input” 接收:this.refs.input
- 字符串方式的ref是最简单的,但是react官方不推荐使用,因为页面上定义多了的话会有效率问题,而且可能会在之后的版本被弃用.
2.回调函数形式的ref
class Demo extends React.Component {
state = { isHot: true }
// 自定义函数要用箭头函数,才能拿到正确的this
showDlg = () => {
alert(this.input1.value)
}
showDlg2 = () => {
alert(this.input2.value)
}
getInptEl = (el) => {
this.input2 = el
}
render() {
const { isHot } = this.state
return (
<div>
{/* 内联函数式的ref */}
<input ref={el => this.input1 = el} type="text" placeholder="点击按钮弹出内容" />
<button onClick={this.showDlg}>点击弹出内容</button>
{/* 外联函数式的ref */}
<input ref={this.getInptEl} type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
</div>
)
}
}
ReactDOM.render(<Demo />, document.getElementById('test1'))
笔记:
1. 回调函数的形式有两种:一种是内联函数ref={el => this.input1 = el}
;另一种外联的,声明ref={this.getInptEl}
,接收getInptEl = (el) => { this.input2 = el }
2. 通常项目中都是采用内联回调的方式.
3. 内联回调在更新的时候会有一点点问题:会被调用两次,第一次拿到的el是null,但是官方说这个影响是无关紧要的.
4. 外联样式没有什么问题,但是比较麻烦,代码不够直观 ===> 项目中使用内联回调式就行!!
3.使用createRef
class Demo extends React.Component {
input1 = React.createRef()
input2 = React.createRef()
showDlg = () => {
// current是固定的
const input = this.input1.current
alert(input.value)
}
showDlg2 = () => {
const input = this.input2.current
alert(input.value)
}
render() {
return (
<div>
<input ref={this.input1} type="text" placeholder="点击按钮弹出内容" />
<button onClick={this.showDlg}>点击弹出内容</button>
<input ref={this.input2} type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
</div>
)
}
}
ReactDOM.render(<Demo />, document.getElementById('test1'))
笔记:
1. 定义:ref={this.input1}
;
2. 接收:input1 = React.createRef()
;
3. 取值:this.input2.current
4. React.createRef
是官方推荐使用的API,注意拿到的DOM是在ref的current
属性里