4. Use Methods
In addition to states and events, a method that can be manually controlled is considered essential to a component.
You can set which functions are exposed with the setMethods
function.
The following code is an example of manually changing the width value through the setWidth
function.
import { reactive } from "@cfcs/core";
const REACTIVE_ADAPTER = ({ setMethods, onInit, onDestroy }) => {
setMethods(["setWidth"]);
const obj = reactive({
width: 0,
height: 0,
setWidth(width) {
obj.width = width;
},
});
const onResize = e => {
obj.width = window.innerWidth;
obj.height = window.innerHeight;
};
onInit(() => {
window.addEventListener("resize", onResize);
});
onDestroy(() => {
window.removeEventListener("resize", onResize);
});
return obj;
};
Frameworks
- React
- Vue@2
- Vue@3
- Svelte
import { useReactive } from "@cfcs/react";
export function App() {
const {
width,
height,
setWidth,
} = useReactive(REACTIVE_ADAPTER);
return <div onClick={() => {
setWidth(200);
}}>{width}x{height}</div>;
}