Reactjs React UseImperializeHandle如何公开DOM和内部方法?
非常简单的问题,我需要使用Reactjs React UseImperializeHandle如何公开DOM和内部方法?,reactjs,react-hooks,Reactjs,React Hooks,非常简单的问题,我需要使用useImperialiveHandle向家长公开内部子方法。 但我也想访问ref.current.style,例如,在使用useImperialiveHandle时,它当前未定义,您知道如何使用内部方法传递它吗 useImperativeHandle(ref, () => ({ someMethod: () => { ... }, ...ref })); 上述方法可行,但
useImperialiveHandle
向家长公开内部子方法。
但我也想访问ref.current.style,例如,在使用useImperialiveHandle
时,它当前未定义,您知道如何使用内部方法传递它吗
useImperativeHandle(ref, () => ({
someMethod: () => {
...
},
...ref
}));
上述方法可行,但这是正确的方法吗?(此外,我们还必须做ref.current.current,这不是很好)
一个简单的例子:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
function FancyParent() {
const childRef = useRef()
useEffect(()=>{
childRef.current.style.opacity = 0;
// oups current.style has been ovveriden and is now
//undefined
})
return <FancyInput ref={childRef}/>
}
函数FancyInput(道具,参考){
const inputRef=useRef();
使用命令式句柄(参考,()=>({
焦点:()=>{
inputRef.current.focus();
}
}));
返回;
}
FancyInput=forwardRef(FancyInput);
函数FancyParent(){
const childRef=useRef()
useffect(()=>{
childRef.current.style.opacity=0;
//oups current.style已经过验证,现在
//未定义
})
返回
}
您实际上覆盖了ref。您希望这样使用:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
opacity: () => {
inputRef.current.style.opacity = 0
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
function FancyParent() {
const childRef = useRef()
useEffect(()=>{
childRef.current.opacity()
})
return <FancyInput ref={childRef}/>
}
此处,childRef.current
表示FancyInput中的ref
<代码>参考当前样式(参考==>childRef.current)
函数FancyParent(){
const childRef=useRef()
const inputRef=childRef.current
useffect(()=>{
inputRef.current.style.opacity=0
})
返回
}
您必须注意childRef
和inputRef
是不同的。但是,您可以使用useImportiveHandle从childRef
公开inputRef
const{useRef,useffect,useImperialiveHandle,forwardRef}=React;
让fancyinport=forwardRef((道具,ref)=>{
const inputRef=useRef();
使用命令式句柄(参考,()=>({
焦点:()=>{
inputRef.current.focus();
},
inputRef:inputRef.current,
}));
返回;
})
函数FancyParent(){
const childRef=useRef()
useffect(()=>{
childRef.current.inputRef.style.opacity=0;
})
返回
}
ReactDOM.render(,document.getElementById('app'))代码>
展示适当的代码示例以说明您的问题。很抱歉,这个例子非常简单,我认为它是不言自明的,我添加了一个简单的例子,让我知道它是否更清楚。但我没有否决你的问题。让我再看一次你的问题,以便我能帮助你。我确认了第一个回答的人,但谢谢你,回答得非常清楚。很高兴能帮助你
childRef.current.current.style.opacity = 0
function FancyParent() {
const childRef = useRef()
const inputRef = childRef.current
useEffect(()=>{
inputRef.current.style.opacity = 0
})
return <FancyInput ref={childRef}/>
}