[英]React-Native: access a function defined inside useEffect() - call it from outside useEffect
有沒有辦法調用在 useEffect 中定義的函數(作為按鈕的回調)?
組件的骨架如下:
useEffect(() => {
const longFunction = async () => {
...
const innerFunctionOne = async () => {
...
}
const innerFunctionTwo = async () => {
...
innerFunctionOne()
}
... some code
... some code
innerFunctionTwo()
}
...some code
longFunction();
return someCleanup;
},[])
...
...
<Button onPress={() => innerFunctionTwo()}
除了在useEffect之外取出函數定義,有沒有辦法從Button訪問它? 謝謝
如果不知道實現的細節,就很難判斷。 因此,在不知道您的詳細信息的情況下,我會將 longFunction 放在 useEffect 之外,將 innerFunctionTwo 放在 longFunction 之外。 例如:
function App() { const innerFnTwo = function() { console.log('innerFnTwo'); }; const longFn = function() { console.log('longFn'); innerFnTwo(); }; React.useEffect(() => { longFn(); }, []); return ( <div> <button onClick={() => innerFnTwo()}>Click me</button> </div> ); } ReactDOM.render( <App />, document.getElementById('root') );
<script src="https://unpkg.com/react@17/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.