Javascript 反应v16–;通过包装器组件将ref从子级传递到父级
我现有的组件层次结构如下所示:Javascript 反应v16–;通过包装器组件将ref从子级传递到父级,javascript,reactjs,ref,react-forwardref,Javascript,Reactjs,Ref,React Forwardref,我现有的组件层次结构如下所示: const Parent=props=>{ const divElement=useRef() //用divElement做点什么 返回 } const Child=React.forwardRef((props,ref)=>{ 返回 } 这一切都很好,但现在我需要有条件地添加一个包装器组件,它包装组件以添加一些特例道具 基本上我想要的是这样的: const Parent=props=>{ const divElement=useRef() //用divElem
const Parent=props=>{
const divElement=useRef()
//用divElement做点什么
返回
}
const Child=React.forwardRef((props,ref)=>{
返回
}
这一切都很好,但现在我需要有条件地添加一个包装器组件,它包装
组件以添加一些特例道具
基本上我想要的是这样的:
const Parent=props=>{
const divElement=useRef()
//用divElement做点什么
返回条件?:
}
const Wrapper=props=>{
返回
}
const Child=React.forwardRef((props,ref)=>{
返回
}
我被困在如何将
ref
从Child
通过Wrapper
传递回Parent
,因此Parent
可以访问Child
的ref
无论Wrapper
是否存在…你不应该将任何东西从孩子传递给父母。当然你可以n使用回调,但您不会使用它们传递引用或类似的内容
您只需将包装也设为ForwardRef:
const Wrapper = React.forwardRef((props, ref) => {
return <Child ref={ref} {...your other props} />
})
const Wrapper=React.forwardRef((props,ref)=>{
返回
})
现在你可以打电话:
return someCondition ? <Wrapper ref={divElement} {...some props} /> : <Child ref={divElement} {...some props} />
returnsomecondition?:
您的ref将始终是您想要的div。除了使用@Reductio所说的
React.forwardRef
之外,您还可以使用自定义道具将ref传递给孩子们,无论是否使用包装器
我从这里学到了:
通过自定义道具传递ref要简单得多。代码如下:
const Parent = props => {
const divElement = useRef()
// do something with divElement
return someCondition ? <Wrapper {...some props} forwardedRef={divElement} /> : <Child forwardedRef={divElement} {...some props} />
}
const Wrapper = props => {
//MAKE SURE "different props" includes the custom props: forwardedRef from props
return <Child {...different props} />
}
const Child =({forwardRef, ...rest}) => {
return <div ref={forwardedRef} {...rest}><some stuff here></div>
}
const Parent=props=>{
const divElement=useRef()
//用divElement做点什么
返回条件?:
}
const Wrapper=props=>{
//确保“不同的道具”包括自定义道具:props中的forwardedRef
返回
}
常量Child=({forwardRef,…rest})=>{
返回
}
WrapWrapper
组件在React.forwardRef()
中。这当然是一个有效的解决方案。我总是更喜欢使用forward ref,因为这只是React中处理ref的正常方式,并且您有一个固定的协议如何传递ref。然而,这更像是一个您可以遵循但不必遵循的准则。