在React中存储函数可以通过以下几种方式实现:
import React, { useState } from 'react';
function MyComponent() {
const [myFunction, setMyFunction] = useState(null);
const handleClick = () => {
const myFunc = () => {
console.log('Hello from stored function!');
};
setMyFunction(myFunc);
};
const handleInvoke = () => {
if (myFunction) {
myFunction();
}
};
return (
<div>
<button onClick={handleClick}>Store Function</button>
<button onClick={handleInvoke}>Invoke Function</button>
</div>
);
}
import React, { createContext, useContext } from 'react';
const MyFunctionContext = createContext(null);
function MyComponent() {
const myFunction = () => {
console.log('Hello from stored function!');
};
return (
<MyFunctionContext.Provider value={myFunction}>
<ChildComponent />
</MyFunctionContext.Provider>
);
}
function ChildComponent() {
const myFunction = useContext(MyFunctionContext);
const handleInvoke = () => {
if (myFunction) {
myFunction();
}
};
return (
<div>
<button onClick={handleInvoke}>Invoke Function</button>
</div>
);
}
import React, { useState } from 'react';
function useStoredFunction() {
const [myFunction, setMyFunction] = useState(null);
const storeFunction = (func) => {
setMyFunction(func);
};
const invokeFunction = () => {
if (myFunction) {
myFunction();
}
};
return [storeFunction, invokeFunction];
}
function MyComponent() {
const [storeFunction, invokeFunction] = useStoredFunction();
const handleClick = () => {
const myFunc = () => {
console.log('Hello from stored function!');
};
storeFunction(myFunc);
};
return (
<div>
<button onClick={handleClick}>Store Function</button>
<button onClick={invokeFunction}>Invoke Function</button>
</div>
);
}
这些方法可以根据具体的需求和场景选择使用。它们都可以在React中有效地存储和调用函数。
领取专属 10元无门槛券
手把手带您无忧上云