基本步骤
- 创建Ref对象:使用
React.createRef()
(在类组件中)或者useRef
Hook(在函数组件中)创建一个Ref对象。
- 关联Ref对象到DOM元素:通过在需要操作的DOM元素上设置
ref
属性,将创建的Ref对象传递给它。
- 使用Ref对象操作DOM:在合适的时机,通过Ref对象访问关联的DOM元素,进而操作它。
示例 - 类组件
import React, { Component } from 'react';
class InputComponent extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleClick = () => {
const inputValue = this.inputRef.current.value;
console.log('Input value is:', inputValue);
}
render() {
return (
<div>
<input type="text" ref={this.inputRef} />
<button onClick={this.handleClick}>Get Value</button>
</div>
);
}
}
export default InputComponent;
示例 - 函数组件
import React, { useRef } from 'react';
const InputComponent = () => {
const inputRef = useRef(null);
const handleClick = () => {
const inputValue = inputRef.current.value;
console.log('Input value is:', inputValue);
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Get Value</button>
</div>
);
}
export default InputComponent;