我在项目中使用带有svelte简单模态的getContext。
有没有办法在Typescript文件中使用getContext等?在Typescript文件中调用svelte函数时,我得到了一个500: Function called outside component initialization
。
我已经尝试了how-do-you-import-a-svelt-component-in-a-typescript-file中提到的方法。
谢谢你的帮助!
您可以在TypeScript文件中使用getContext
,但只能在组件初始化期间调用它,也就是第一次运行组件脚本标记的内容时。
// TS code
import { getContext } from 'svelte';
export function getFooContext() {
const foo = getContext('foo');
}
export function fails() {
setTimeout(() => getFooContext(), 100);
}
// Svelte code
<script>
import { getFooContext } from './somewhere';
// this is ok
getFooContext();
// this fails because it's called after the component is initialized
setTimeout(() => getFooContext(), 100);
// this fails because the function has a setTimout which is resolved
// after the component is initialized
fails();
</script>
您不能在组件初始化之外调用getContext
或setContext
或Svelte的任何生命周期函数,这意味着您不能将其称为
- 异步(例如超时后(
- 响应组件的DOM事件
- 等等