方法一:React.createRef()
- 用于HTML元素上 其current 属性 值为 DOM 元素
- 自定义 class 组件 值为 组件的挂载实例
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
getRef(){
const node = this.myRef.current;
}
render() {
return <div ref={this.myRef} />;
}
}
方法二:ref属性赋值 不建议使用,有可能会存在 一些问题,可能会被移除
- 用于HTML元素上 其this.refs.名 值为 DOM 元素
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
getRef(){
const node = this.refs.myRef;
}
render() {
return <div ref='myRef' />;
}
}
方法三:Refs回调
使用 ref 回调函数,在实例的属性中存储对 DOM 节点的引用。
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// 使用原生 DOM API 使 text 输入框获得焦点
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// 组件挂载后,让文本框自动获得焦点
this.focusTextInput();
}
render() {
// 使用 `ref` 的回调函数将 text 输入框 DOM 节点的引用存储到 React
// 实例上(比如 this.textInput)
return (
<div>
<input
type="text"
ref={this.setTextInputRef}
/>
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
这种方式还可以实现 子组件向父组件暴露其ref
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
// this.inputElement 储存了子组件input元素
本文详细介绍了React中三种创建和使用ref的方法:React.createRef(),ref属性赋值以及ref回调函数。分别阐述了它们在HTML元素和自定义组件上的应用,以及如何通过ref实现子组件向父组件的通信。
150

被折叠的 条评论
为什么被折叠?



