推荐用于 16.3 之前的 React 版本
如果无法避免,则从建议的模式中提取反应文档将会:
import React, { Component } from 'react';
const Child = ({ setRef }) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Calling a function on the Child DOM element
this.childRef.focus();
}
setRef(input) {
this.childRef = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
The Parent将函数作为 prop 转发到Parent's this
。当 React 调用Child's ref
prop setRef
它将分配Child's ref
to the Parent's childRef
财产。
推荐用于 React >= 16.3
引用转发是一种选择加入的功能,它允许某些组件获取它们收到的引用,并将其进一步向下传递(换句话说,“转发”)给子组件。
我们创造成分转发他们的ref
with React.forwardRef
。
返回的成分ref 属性必须与返回类型相同React.createRef
。每当 React 安装 DOM 节点时,属性current
of the ref
创建于React.createRef
将指向底层 DOM 节点。
import React from "react";
const LibraryButton = React.forwardRef((props, ref) => (
<button ref={ref} {...props}>
FancyButton
</button>
));
class AutoFocus extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
this.onClick = this.onClick.bind(this);
}
componentDidMount() {
this.childRef.current.focus();
}
onClick() {
console.log("fancy!");
}
render() {
return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
}
}
转发参考 HOC 示例
Created 成分正在转发他们的ref
到子节点。
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
See 转发参考文献在 React 文档中。