React refs All In One
React refs All In One
DOM ref
useRef 👍✅
https://reactjs.org/docs/forwarding-refs.html
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
https://reactjs.org/docs/refs-and-the-dom.html#refs-and-function-components
function MyFunctionComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// This will *not* work!
return (
<MyFunctionComponent ref={this.textInput} />
);
}
}
React.createRef 👍✅
https://reactjs.org/docs/refs-and-the-dom.html#creating-refs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
render() {
return <input type="text" ref={this.inputRef} />;
}
componentDidMount() {
this.inputRef.current.focus();
}
}
callback ref 👍✅
https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
string ref 👎❌
https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs
refs
strict mode
https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13732934.html
未经授权禁止转载,违者必究!

浙公网安备 33010602011771号