- 字符串形式(不推荐)
class Demo extends React.Component {
showDate = () => {
const {input1} = this.refs
alert(input1.value)
}
showData2 = () => {
const {input2} = this.refs
alert(input2.value)
}
render(){
return (
<div>
<input ref='input1'/>
<button onClick={this.showData}>点击显示左侧输入框内容</button>
<input ref='input2' onBlur = {this.showData2}/>
</div>
)
}
}
- 回调函数形式
class Demo extends React.Component {
showDate = () => {
const {input1} = this
alert(input1.value)
}
showData2 = () => {
const {input2} = this
alert(input2.value)
}
render(){
return (
<div>
<input ref={current => this.input1 = current}/>
<button onClick={this.showData}>点击显示左侧输入框内容</button>
<input ref={current => this.input2 = current} onBlur = {this.showData2}/>
</div>
)
}
}
- createRef创建ref
使用React.createRef()可以创建一个容器,该容器可以储存被ref所标识的节点,但只能储存一个,所以需要储存多个节点时需要创建多个容器。
class Demo extends React.Component {
myRef = React.createRef()
myRef2 = React.createRef()
showDate = () => {
alert(this.myRef.current.value)
}
showData2 = () => {
alert(this.myRef2.current.value)
}
render(){
return (
<div>
<input ref={this.myRef}/>
<button onClick={this.showData}>点击显示左侧输入框内容</button>
<input ref={this.myRef2} onBlur = {this.showData2}/>
</div>
)
}
}