Context
Mitosis的context必须是:
- 在自己的文件中创建
- 文件名必须以context.lite.ts结尾
- 默认导出必须是一个返回context对象的函数
// simple.context.lite.ts
import {
createContext } from '@builder.io/mitosis';
export default createContext({
foo: 'bar',
get fooUpperCase() {
return this.foo.toUpperCase();
},
someMethod() {
return this.fooUpperCase.toLowercase();
},
content: null,
context: {
} as any,
state: {
},
});
然后你可以在组件中使用它
import Context from './simple.context.lite';
import {
useContext, setContext } from '@builder.io/mitosis';
export default function ComponentWithContext(props: {
content: string }) {
// you can access the context using `useContext`
const foo = useContext(Context);
// you can use `setContext` to provide a new value for the context
setContext(Context, {
foo: 'baz',
content() {
return props.content;
},
});
return (
// you can also use `Context.provider` to provide a new value for the context
<Context.Provider value={
{
bar: 'baz' }}>{
foo.value}</Context.Provider>
);
}