如果无法避免,那么从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} /> }}
该 家长 转发绑定到一个功能道具 家长
this。当呼叫作出反应的 儿童的
ref道具
setRef也将分配
孩子的
ref给 父母的
childRef财产。建议用于React> = 16.3
引用转发是一种选择加入功能,它使某些组件可以接收它们收到的引用,并将其进一步向下传递(即“转发”)给孩子。
我们创建 的组件 可以转发他们
ref用
React.forwardRef。返回的 Component ref
prop必须与的返回类型相同
React.createRef。每当React装入DOM节点
current时,
ref创建的with的属性都
React.createRef将指向基础DOM节点。
转发参考HOC示例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} />; }}
创建的 组件 将其转发
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} />; });}
请参阅React文档中的转发参考。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)