乐闻世界logo
搜索文章和话题

React 怎么传递 ref 给兄弟组件?

4 个月前提问
3 个月前修改
浏览次数42

1个答案

1

在React中,ref 通常用于获取DOM节点或者创建对组件的引用。但是,ref 并不是一个可以像props那样直接传递给兄弟组件的属性。尽管如此,我们可以通过一些间接的方式来实现这一目的。以下是几种在React中传递ref给兄弟组件的方法:

方法一:使用 React.createRef() 和父组件作为中介

我们可以在父组件中创建一个ref,然后将这个ref通过props传递给任何子组件。这里的关键是父组件作为中介。

示例代码

jsx
import React, { createRef, Component } from 'react'; class ParentComponent extends Component { nodeRef = createRef(); render() { return ( <div> <ChildA ref={this.nodeRef} /> <ChildB nodeRef={this.nodeRef} /> </div> ); } } const ChildA = React.forwardRef((props, ref) => ( <input ref={ref} /> )); function ChildB({ nodeRef }) { function handleClick() { if (nodeRef.current) { nodeRef.current.focus(); // 使用传递来的 ref 调用方法 } } return <button onClick={handleClick}>Focus on input in ChildA</button>; }

在这个例子中,ChildA 组件通过React.forwardRef接收ref,而ChildB通过props接收相同的ref。然后ChildB可以使用这个ref来操作ChildA的DOM元素。

方法二:使用 Context API

如果项目结构复杂或组件层级较深,可以使用React的Context API来跨组件层级传递数据(包括ref)。

示例代码

jsx
import React, { createContext, useRef, useContext } from 'react'; const RefContext = createContext(null); function ParentComponent() { const sharedRef = useRef(null); return ( <RefContext.Provider value={sharedRef}> <ChildA /> <ChildB /> </RefContext.Provider> ); } const ChildA = () => { const inputRef = useContext(RefContext); return <input ref={inputRef} />; }; function ChildB() { const inputRef = useContext(RefContext); function handleClick() { if (inputRef.current) { inputRef.current.focus(); } } return <button onClick={handleClick}>Focus on input in ChildA</button>; }

在这种方法中,ref被放在Context中,然后通过Provider向下传递。这使得任何消费者组件都可以访问这个ref并与之交互。

总结

虽然React不允许直接将ref作为props传递给兄弟组件,但我们可以利用父组件作为中介或使用Context API来间接实现这一功能。两种方法都可以根据具体的应用场景和需求来选择使用。

2024年6月29日 12:07 回复

你的答案