Javascript 是否可以向props.children元素添加ref?
我有一个表单和输入组件,如下所示Javascript 是否可以向props.children元素添加ref?,javascript,reactjs,react-redux,react-hooks,Javascript,Reactjs,React Redux,React Hooks,我有一个表单和输入组件,如下所示 <Form> <Field /> <Field /> <Field /> </Form> 表单组件将充当此处的包装组件,而字段组件引用未在此处设置。我希望迭代表单中的props.children子组件,并希望为每个子组件分配一个ref属性。是否有可能实现这一点?您需要表单向您的refs注入React.Children和React.cloneElementAPI: const Fu
<Form>
<Field />
<Field />
<Field />
</Form>
表单组件将充当此处的包装组件,而字段组件引用未在此处设置。我希望迭代表单中的props.children子组件,并希望为每个子组件分配一个ref属性。是否有可能实现这一点?您需要
表单
向您的refs注入React.Children
和React.cloneElement
API:
const FunctionComponentForward = React.forwardRef((props, ref) => (
<div ref={ref}>Function Component Forward</div>
));
const Form = ({ children }) => {
const childrenRef = useRef([]);
useEffect(() => {
console.log("Form Children", childrenRef.current);
}, []);
return (
<>
{React.Children.map(children, (child, index) =>
React.cloneElement(child, {
ref: (ref) => (childrenRef.current[index] = ref)
})
)}
</>
);
};
const App = () => {
return (
<Form>
<div>Hello</div>
<FunctionComponentForward />
</Form>
);
};
const FunctionComponentForward=React.forwardRef((props,ref)=>(
功能组件转发
));
常量形式=({children})=>{
const childrenRef=useRef([]);
useffect(()=>{
log(“formchildren”,childrenRef.current);
}, []);
返回(
{React.Children.map(Children,(child,index)=>
反应。克隆元素(儿童{
ref:(ref)=>(childrenRef.current[index]=ref)
})
)}
);
};
常量应用=()=>{
返回(
你好
);
};
您可以使用中显示的两种方法之一映射子对象,并基于该子对象创建组件的新实例
- 使用
和React.Children.map
(这样可以保留原始元素的键和引用)React.cloneElement
- 或者仅使用
(仅保留来自原始组件的引用)React.Children.map
函数useRefs(){
const refs=useRef({});
常量寄存器=useCallback((refName)=>ref=>{
refs.current[refName]=ref;
}, []);
返回[参考文献,寄存器];
}
没有CloneComponent({children,…props})的函数{
const[refs,register]=useRefs();
返回(
{React.Children.map((子对象,索引)=>(
)}
)
}
带有CloneComponent({children,…props})的函数{
const[refs,register]=useRefs();
返回(
{
React.Children.map((子级,索引)=>React.cloneElement(
小孩
{ref:register(`field-${index}`,…child.props)
)
}
)
}
我正在获取此警告索引。js:1警告:无法为功能组件提供引用。尝试访问此引用将失败。是否要使用React.forwardRef()?在我的示例中,我将ref传递给div
,当您传递给函数组件时,您需要使用forwardRef
或使用其他类似innerRef
的道具并传递ref。我添加了一个示例,您只需查找“将ref传递给函数组件”。
function useRefs() {
const refs = useRef({});
const register = useCallback((refName) => ref => {
refs.current[refName] = ref;
}, []);
return [refs, register];
}
function WithoutCloneComponent({children, ...props}) {
const [refs, register] = useRefs();
return (
<Parent>
{React.Children.map((Child, index) => (
<Child.type
{...Child.props}
ref={register(`${field-${index}}`)}
/>
)}
</Parent>
)
}
function WithCloneComponent({children, ...props}) {
const [refs, register] = useRefs();
return (
<Parent>
{
React.Children.map((child, index) => React.cloneElement(
child,
{ref: register(`field-${index}`, ...child.props
)
}
</Parent>
)
}