传送 ref 是一种自动把 ref 从一个 component 传递到它底下的其中一个 child 的技巧。通常来说,应用程序里大部分的 component 都不需要用到它。然而,对某些种类的 component 来说它很有用,特别是能够重复使用的函式库。以下会解释最常见的情形。
有几种使用 ref 的情况:
以下一个 focus 的例子,使用 ref 触发 focus 事件:
const FormInput = React.forwardRef((props, ref) => (
<input ref={ref} className="FancyText" type="text" id="myTextField" value={props.children} />
));
class App extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
this.focusMethod = this.focusMethod.bind(this);
}
focusMethod() {
this.ref.current.focus()
}
render() {
return (
<div className="App">
<FormInput ref={this.ref}>我是一些输入</FormInput>
<button type="button" onClick={this.focusMethod}>点我 Focus!</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
在 DevTool 里面查看 displayName 的例子:
function FormInput(props, ref) {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
}
const FancyInput = React.forwardRef(FormInput);
function App() {
const ref = React.useRef();
function handleFocus() {
ref.current.focus();
}
return (
<div className="App">
<FancyInput ref={ref} placeholder="my input" />
<button onClick={handleFocus}>Focus</button>
</div>
);
}
以上今天。
参考资料:
https://zh-hant.reactjs.org/docs/forwarding-refs.html
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
https://blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/
Colab连结 今天的主题比较特殊一些,要来探讨 tensorflow 中的 Dataset api...
Azure machine learning: Schedule- Azure 为你定期执行任务 前...
前言 记得以前在学校的时候修过资料结构与演算法,考试也都会考时间复杂度等相关的题目 毕业後,在公司上...
可曾想过,我所住的社区有什麽? 什麽是社区 在本文章的定义引自 wiki_社区 提到的,因为共享共同...
前言 「重复」页面的画面已经完成了,接着实作功能吧! 功能图: 实作 首先建立一个变数,用来储存Ce...