Methods
状态对象还可以接受方法:
export default function MyComponent() {
const state = useStore({
name: 'Steve',
updateName(newName) {
state.name = newName;
},
});
return (
<div>
<h2>Hello, {state.name}</h2>
<input onInput={(event) => state.updateName(event.target.value)} value={state.name} />
</div>
);
}
条件&列表渲染
Builder中的控制流像Solid一样是静态的。你必须使用控制流组件,如和,而不是像React中那样使用自由格式的javascript。
- 条件渲染
条件渲染使用Show,它需要一个独特的参数 when作为匹配条件,匹配成功则渲染,反之不渲染。
export default function MyComponent(props) {
return <Show when={props.showContents}>Hello, I may or may not show!</Show>;
}
- 列表渲染
使用For进行列表渲染,它接受一个each参数,作为即将渲染的列表数据。该组件的child接受一个方法,将子项和对应的索引作为参数,并返回渲染内容。例如:
export default function MyComponent(props) {
const state = useStore({
myArray: [1, 2, 3],
});
return <For each={state.myArray}>{(theArrayItem, index) => <div>{theArrayItem}</div>}</For>;
}
给组件传递参数使用props
export default function MyComponent(props) {
return <div>{props.children}</div>;
}
对于Web Comonent,你需要使用ShadowDom元数据。
import { useMetadata } from '@builder.io/mitosis';
useMetadata({
isAttachedToShadowDom: true,
});
export default function MyComponent(props) {
return <div>{props.children}</div>;
}
Slot
当你想要定义一个具名插槽时,你可以使用slot props。
<div>
<Layout
slotTop={<NavBar/>}
slotLeft={<Sidebar/>}
slotCenter={<Content/>}
/>
anything else
</Layout>
</div>
在上述例子中将布局组件的上左中注册为插槽。如果插入的组件也是一个Mitosis组件的话,只需要使用props中的引用即可。
<div class="layout">
<div class="top"><slot name="top" /></div>
<div class="left"><slot name="left" /></div>
<div class="center"><slot name="center" /></div>
<slot />
</div>
}
对于vue组件,slot props将被编译到具名插槽中
<div class="layout">
<div class="top"><slot name="top" /></div>
<div class="left"><slot name="left" /></div>
<div class="center"><slot name="center" /></div>
<slot />
</div>
}