如何使用react hook获得儿童的ref



我正在尝试获取子组件的ref,但它似乎不起作用。同样的方法适用于React类组件,但不适用于钩子。

import React, { useState, useRef } from "react";
export default function TestContainer(props) {
const ref = useRef(null);
return (
<div className="test-container" onClick={() => console.log(ref) // this logs null always}>
{React.Children.map(props.children, c =>
React.cloneElement(c, {
ref: n => {
console.log(n);
ref.current = n;
},
className: "test-container"
})
)}
</div>
);
}
export function Test(props) {  
return <div className="test" {...props}>
{props.children}
</div>
}

您的组件正常。这可能是因为没有子级渲染到该组件。我在App中使用TestContainer复制了它,并将<h2>Ref</h2>作为TestContainer:的子代

(当然删除了评论,因为它一直隐藏着}(

App.js

import React from "react";
import "./styles.css";
import TestContainer from "./TestContainer";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<TestContainer>
<h2>Ref</h2>
</TestContainer>
</div>
);
}

TestContainer.js

import React, { useState, useRef } from "react";
export default function TestContainer(props) {
const ref = useRef(null);
return (
<div className="test-container" onClick={() => console.log(ref)}>
{React.Children.map(props.children, c =>
React.cloneElement(c, {
ref: n => {
console.log(n);
ref.current = n;
},
className: "test-container"
})
)}
</div>
);
}

CodeSndbox:

这里

相关内容

  • 没有找到相关文章

最新更新