一组用于用React构建ui的实用程序
v1.2.0
npm i 0ui
查看如何将所有东西一起使用的示例 example/src/index.js
构建UMD格式
<script src="https://unpkg.com/0ui/dist/0ui.umd.js"></script>
核心自由
lib/core.js
随机工具
愚蠢的模式匹配
更像是一个简写 switch/case
import { match } from "0ui/lib/core";
match("loading")({
loading: () => console.log("Loading"),
error: () => console.log("Error")
});
// "Error"
imtbl
纯JavaScript对象的不可变样式数据操作,参见 imtbl 自由。
状态
lib/state.js
状态对象
独立状态对象
import State from "0ui/lib/state";
const state = State.create(0);
state.addWatch("key", (key, state, prevVal, nextVal) => {
console.log(prevVal, nextVal);
});
state.swap(val => val + 1); // 0 1
派生的状态
lib/derived-state.js
使用函数派生state ->状态,并从state ->状态传播更新。
import State from "0ui/lib/state";
import DerivedState from "0ui/lib/derived-state";
const bucket = State.create({
items: [
{
price: 104.5
},
{
price: 78.2
}
]
});
const bucketPrice = DerivedState.create(bucket, ({ items }) =>
items.reduce((sum, { price }) => sum + price, 0)
);
bucketPrice.state; // 182.7
bucket.swap(removeFirstItem);
bucketPrice.state; // 178.2
多重方法
lib/multimethod.js
多分派或多方法是一些编程语言的特性,其中可以根据运行时(动态)类型动态分派函数或方法,或者在更一般的情况下,根据其多个参数的其他属性动态分派函数或方法。 维基百科
import MultiMethod from "0ui/lib/multimethod";
const toJSON = MultiMethod.create(v => {
if (Array.isArray(v)) {
return "array";
} else {
return typeof v;
}
});
toJSON.addMethod("string", v => JSON.stringify(v));
toJSON.addMethod("number", v => v.toString());
toJSON.addMethod("array", arr => {
const jsonArr = arr.map(v => toJSON.dispatch(v)).join(", ");
return `[${jsonArr}]`;
});
toJSON.addMethod("object", o => {
const jsonObj = Object.entries(o)
.map(([k, v]) => toJSON.dispatch(k) + ":" + toJSON.dispatch(v))
.join(", ");
return `{${jsonObj}}`;
});
toJSON.dispatch({
items: [1, "two"]
});
// {"items":[1, "two"]}
用户界面
lib/ui.js
React组件API包装器。订阅多个State对象。
import { createComponent } from "0ui/lib/ui";
import State from "0ui/lib/state";
const Counter = createComponent({
states: {
count: State.create(0) // local state
},
render(states, props) {
const { count } = states;
return (
<div>
<button onClick={() => count.swap(v => v - 1)}>-</button>
<span>{count.state}</span>
<button onClick={() => count.swap(v => v + 1)}>+</button>
</div>
);
}
});