如果我有类似的东西
<Parent> <Child1 /> <Child2 /> <Child3 /> </Parent>
我想从Child2我拥有的地方访问refs="child2refs",该怎么办?
Child2
refs="child2refs"
如果无法避免,那么从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财产。
this
ref
setRef
childRef
引用转发是一种选择加入功能,它使某些组件可以接收它们收到的引用,并将其进一步向下传递(即“转发”)给孩子。
我们创建 的组件 可以转发他们ref用React.forwardRef。返回的 Component ref prop必须与的返回类型相同React.createRef。每当React装入DOM节点current时,ref创建的with的属性都React.createRef将指向基础DOM节点。
React.forwardRef
React.createRef
current
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文档中的转发参考。