javascript - React forwardRef 含义
问题描述
我不明白这是什么意思:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
如果我能做到这一点:
function FancyButton(props) {
return (
<button className="FancyButton" ref={props.ref}>
{props.children}
</button>
);
}
解决方案
从文件
Ref 转发是一种通过组件自动将 ref 传递给它的一个子组件的技术。
Ref forwarding 是一种可选功能,它允许某些组件获取它们接收到的 ref,并将其进一步向下传递(换句话说,“转发”它)给子级。
对于你的问题
我不明白这是什么意思:如果我能做到这一点:。
您可以选择第一种方法或第二种方法
例子
// EmailInput wraps an HTML `input` and adds some app-specific styling.
const EmailInput = React.forwardRef((props, ref) => (
<input ref={ref} {...props} type="email" className="AppEmailInput" />
));
class App extends Component {
emailRef = React.createRef();
render() {
return (
<div>
<EmailInput ref={this.emailRef} />
<button onClick={() => this.onClickButton()}>
Click me to focus email
</button>
</div>
);
}
// `this.emailRef.current` points to the `input` component inside of EmailInput,
// because EmailInput is forwarding its ref via the `React.forwardRef` callback.
onClickButton() {
this.emailRef.current.focus();
}
}
对我来说,fowardRef 不需要太多,因为我们总是可以使用另一种方法传递 ref
你可以在这里阅读更多
推荐阅读
- javascript - TypeError: _this2 is undefined REACTJS
- python - 可安装包不在 pypi 中
- javascript - array.reduce() 在多个参数上使用索引
- c# - 更新属性时出现 DeviceTwin 问题
- domain-driven-design - 使用值对象验证实体的性能问题
- jquery - Ajax 查询未捕获参考
- c# - C#如何不间断地运行多个任务
- firebase - Firestore IN 运算符不与布尔运算符一起使用
- pip - 安装用于 OpenAI Gym 的 Box2D Python 包时出错
- r - 在 R 中正确添加月份