- 字符串形式的ref
class Demo extends React.Component{
showData = () =>{
const {input1} = this.refs
alert(input1.value)
}
showData2 = () =>{
const {input2} = this.refs
alert(input2.value)
}
render() {
return (
<div>
<input type="text" placeholder="点击按钮提示数据" ref="input1" />
<button onClick={this.showData}>点击我提示左边的数据</button>
<input type="text" placeholder="失去焦点提示数据" onBlur={this.showData2} ref="input2" />
</div>
)
}
}
ReactDOM.render(<Demo />,document.getElementById("text"))
- 回调函数形式的ref
class Demo extends React.Component{
showData = () =>{
const {input1} = this
alert(input1.value)
}
showData2 = () =>{
const {input2} = this
alert(input2.value)
}
saveInput = (c) =>{
this.input1 =c;
console.log(c)
}
render() {
return (
<div>
{}
<input type="text" placeholder="点击按钮提示数据" ref={this.saveInput} /> {}
<button onClick={this.showData}>点击我提示左边的数据</button>
<input type="text" placeholder="失去焦点提示数据" onBlur={this.showData2} ref={currentNode => this.input2 = currentNode} />
</div>
)
}
}
ReactDOM.render(<Demo />,document.getElementById("text"))
- createRef
class Demo extends React.Component{
myRef = React.createRef()
showData = () =>{
console.log(this.myRef.current.value)
}
render() {
return (
<div>
<input type="text" placeholder="点击按钮提示数据" ref={this.myRef} />
<button onClick={this.showData}>点击我提示左边的数据</button>
</div>
)
}
}
ReactDOM.render(<Demo />,document.getElementById("text"))