如果我有

<Parent>
  <Child1 />
  <Child2 />
  <Child3 />
</Parent>

我想从Child2refs="child2refs",我该怎么做?

推荐答案

建议用于16.3之前的React版本

如果无法避免,则从React docs中提取的建议模式为:

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} />
    }
}

Parent将函数作为props 转发到Parent's this.当React调用Child's ref prop setRef时,它会将Child's ref分配给Parent's childRef属性.

建议用于react >=16.3

Ref-forwarding是一种 Select 性加入功能,允许一些组件获取他们接收到的Ref,并将其进一步向下传递(换句话说,"转发"给子组件).

我们创建了Components个,将其ref个和React.forwardRef个向前推进.

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} />;
  }
}

转发refs HOC示例

创建的Components正在将其ref转发到子 node .

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 docs中的Forwarding Refs.

Reactjs相关问答推荐

TypeError:SearchProduct.get()获得了意外的关键字参数查询'

react 路由GUGUD Use Effect无法通过useNavigate正常工作

在构建或部署Reaction应用程序时出错

为什么React UseEffect挂钩在页面重新加载时运行

在reduce()方法上得到NaN

如何解决使用react-hook-form和yup动态创建的输入不集中的问题

画布:用鼠标绘制形状时重新绘制整个画布会导致卡顿

当`useSelector`回调中的属性值更新时,将会使用更新后的值吗?

无法从子组件传递数据到父组件

无法设置 null 的属性(设置src)

使用状态与复选框不同步

将props 传递给 NextJS 布局组件

如何在react 中正确销毁上下文?

如何在 React map 函数循环中使用
标签

将 ref 赋予功能组件以使用内部功能

更新 Next.js 路由查询更改的状态会导致无限循环

React Native PermissionsAndroid 不包括 READ_MEDIA_IMAGES.如何解决这个问题?

react-markdown 不渲染 Markdown

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

如何在组件文件夹内的react 组件文件中导入外部css文件?