我在navigator
中有两个嵌套的屏幕,我希望使用从其中一个屏幕到另一个屏幕(从Screen1.js
到Screen2.js
(的函数。我想在Screen2.js
中调用的函数是addList()
。这是Screen1.js
export default function Screen1({navigation}){
//...
function addList (list){
//Code...
};
//...
}
我已经尝试导入函数addList
,并在Screen2
:中这样使用它
import addList from './Screen1
//...
export default function Screen2({navigation}){
//...
function createSomething(){
//...
addList(list);
//...
}
//...
}
然而,我的尝试没有成功。我该如何表演才能做到这一点?
addList应该在父组件中。通过这种方式,您可以在屏幕1和屏幕2中作为道具传递功能。
如果我用Ajmal解决方案做你想做的,我认为它应该是:
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'
const { forwardRef, useRef, useImperativeHandle } = React;
// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Screen1 = forwardRef((props, ref) => {
// The component instance will be extended
// with whatever you return from the callback passed
// as the second argument
useImperativeHandle(ref, () => ({
addList() {
alert("getAlert from Child");
}
}));
return <h1>Hi</h1>;
});
const Screen2 = (props) => {
return (
<div>
....
<button onClick={(e) => props.screen1Ref.addlist(...)}>addList</button>
</div>
)
}
const Parent = () => {
// In order to gain access to the child component instance,
// you need to assign it to a `ref`, so we call `useRef()` to get one
const screen1Ref = useRef();
return (
<div>
<Screen1 ref={screen1Ref} />
<Screen2 screen1Ref={screen1Ref} />
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
现在,在screen2中,您可以调用props.screen1Ref.addList(…(