Refs是什么?
Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
何时适合使用 Refs?
- 管理焦点,文本选择或媒体播放。
- 触发强制动画
- 集成第三方 DOM 库。
Refs有哪些使用方式?
- 原生DOM元素上使用Ref
- 类组件上使用Ref
- 函数组件上使用Ref
- 高阶组件上使用Ref
- 函数组件使用HOOK useRef
import React, { Component, useRef } from "react";
export default class RefPage extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
this.nameInputRef = React.createRef();
this.passwordRef = React.createRef();
this.ageInputRef = React.createRef();
this.countryRef = React.createRef();
}
submit = (e) => {
const name = this.nameInputRef.current.value;
const password = this.passwordRef.current.getPassword();
const age = this.ageInputRef.current.value;
let country = this.countryRef.current.value;
console.log("Submit", name, password, age, country); //, password, age, country, galaxy);
};
render() {
const AgeInputRef = React.forwardRef(AgeInput);
const HocCountry = hoc(CountryInput);
return (
<div>
<div>
<label htmlFor="">姓名</label>
<input type="text" ref={this.nameInputRef} />
</div>
<PasswordInput ref={this.passwordRef} />
<AgeInputRef ref={this.ageInputRef} />
<BirthInput />
<CityInput />
<HocCountry label="国家" ref={this.countryRef} />
<div>
<button onClick={this.submit}>提交</button>
</div>
</div>
);
}
}
class PasswordInput extends Component {
constructor(props) {
super(props);
this.passwordInputRef = React.createRef();
}
getPassword = () => {
return this.passwordInputRef.current.value;
};
render() {
return (
<div>
<div>
<label htmlFor="">密码</label>
<input type="text" ref={this.passwordInputRef} />
</div>
</div>
);
}
}
function AgeInput(props, ref) {
return (
<div>
<label htmlFor="">年龄</label>
<input type="text" ref={ref} />
</div>
);
}
class BirthInput extends Component {
constructor(props) {
super(props);
this.birthInput = null;
}
setTextInputRef = (ele) => {
console.log("setTextInputRef=======", ele);
this.birthInput = ele;
};
componentDidMount() {
this.birthInput.value = "123";
this.birthInput.focus();
}
render() {
return (
<div>
<div>
<label htmlFor="">生日</label>
<input type="text" ref={this.setTextInputRef} />
{/* 不建议使用内联 */}
<input
type="text"
ref={(ele) => {
console.log("setTextInputRef", ele);
this.birthInput = ele;
}}
/>
<button
onClick={() => {
let val = this.birthInput.value;
console.log("birth", val);
}}
>
Click
</button>
</div>
</div>
);
}
}
//hook用法
function CityInput(props) {
const ref = useRef(null);
return (
<div>
<label htmlFor="">区域</label>
<input type="text" ref={ref} />
<button
onClick={() => {
const value = ref.current.value;
console.log("city", value); //sy-log
}}
>
click
</button>
</div>
);
}
const hoc = (WrapComponent) =>
React.forwardRef((props, ref) => {
return (
<div>
<WrapComponent {...props} countryInputRef={ref} />
</div>
);
});
function CountryInput({ label, countryInputRef }) {
return (
<div>
<label htmlFor="">{label}</label>
<input type="text" ref={countryInputRef} />
</div>
);
}
本文是基于React17.0版本
网友评论