在 React.js 中转发 ref
传递给子组件的 ref 被称为转发 ref。React 提供了一个 createRef 函数来为元素创建一个 ref。
forwardRef 是一个传递 ref 给子组件的函数。
示例
// ExampleRef.js
const ExampleTextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="Welcome" ref={ref} />
));
const exampleInputRef = React.createRef();
class NewTextInput extends React.Component {
handleFormSubmit = e => {
e.preventDefault();
console.log(“Entered value: ”+exampleInputRef.current.value);
};
render() {
return (
<div>
<form onSubmit={e => this.handleFormSubmit(e)}>
<NewTextInput ref={exampleInputRef} />
<button>Submit</button>
</form>
</div>
);
}
}顾名思义,ref 转发只是接收 ref 并将其传递给子组件。
ExampleTextInput 中的子组件 input 通过 React.forwardRef 函数接收 ref。
创建 forwardref 的步骤
- React.createRef 用于为元素创建一个 ref 并将其分配给变量 element
- 使用作为 jsx 属性将上面创建的 ref 附加到组件
- 使用 ref 的组件具有 一个 forwardref 函数,该函数接受 props 和 ref 作为参数。
- ref 参数被传递给子组件
- 子组件将 ref 用作 jsx 属性
- 我们通过指定它为 JSX 属性将此 ref 参数转发到 <button ref={ref}>。
- 当 ref 附加时,ref.current 将指向 <button> DOM 节点。
配合高阶组件使用 forwardRef −
示例
const InputHoc = ProvidedComponent => {
const forwardRef = (props, ref) => {
const onValueInput = () => console.log(“ref value: ”+ref.current.value);
return < ProvidedComponent
forwardedRef={ref}
onChange={onValueInput}
{...props} />;
};
return React.forwardRef(forwardRef);
};
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP