如何提供对子元素的引用



我有两个函数:

export default function Example() {
return (
<Widget>
<img src="/hello" />
</Widget>
)
}
export default function Widget() {
const ref = useRef(null)
return (
<div>
{children}
</div>
)
}

如何将"ref"应用于Example的图像元素?是否有一种方法可以始终将其应用于第一个子元素?

您可以使用cloneElement,它可以帮助我们以元素为起点克隆并返回新的React元素。通过这个方法,我们可以将ref添加到元素道具中,首先,我们制作了一个children数组,然后将我们的ref添加到第一个,例如:

function Wrapper({ children }) {
const testRef = React.useRef(undefined);
const addReftoFirstChild = (chilrens, ref) => {
let elements = React.Children.toArray(chilrens);
return [React.cloneElement(elements[0], { ref })].concat(elements.slice(1));
};
return (
<>
{addReftoFirstChild(children, testRef)}
<button onClick={() => console.log(testRef.current)}>Test Ref!</button>
</>
);
}
function App() {
return (
<Wrapper>
<img
src='https://www.publicdomainpictures.net/pictures/80000/velka/odd-eyed-kitten.jpg'
width={200}
height={125}
/>
<img
src='https://c.files.bbci.co.uk/12A9B/production/_111434467_gettyimages-1143489763.jpg'
width={200}
height={125}
/>
</Wrapper>
);
}

您可以使用React的上下文。

const MyContext = React.createContext();
function Widget(props) {
const myRef = useRef(null);
useEffect(() => {
myRef.current.focus();
});
return (
<MyContext.Provider value={myRef}>{props.children}</MyContext.Provider>
);
}
function Example() {
return (
<Widget>
<MyContext.Consumer>
{(forwardedRef) => <input type="text" ref={forwardedRef} />}
</MyContext.Consumer>
</Widget>
);
}

我为您创建了一个演示:https://codesandbox.io/s/prod-voice-mkrcp

最新更新