Storybook 状态
警告
Storybook 最近引入了一种构建插件的新方法,最新版本的 storybook-state 将与 Storybook 版本 > v5.2.*
兼容。对于旧版本的 Storybook,请使用此插件的 v1.3.6
版本。
入门指南
npm install --save-dev @sambego/storybook-state
首先,你需要创建一个新的 store 来保存状态并处理更新。你可以添加组件期望的所有属性,State 组件会将它们传播到你的组件。创建 store 后,你可以将组件包装在 State
组件中并传递 store。
在下面的示例中,我们创建一个 modal,它将期望一个 active
属性。当点击按钮时,我们将更新 store,store 反过来会更新 modal 上的 active
属性;
使用 State 组件显示和更新
import React from "react";
import { storiesOf } from "@storybook/react";
import { State, Store } from "@sambego/storybook-state";
const store = new Store({
active: false
});
const SimpleModal = props => (
<div>
<State store={store}>
<Modal>Modal content</Modal>
</State>
<Button onClick={() => store.set({ active: !store.get("active") })} />
</div>
);
export default { title: "Modal" };
export const Simple = () => SimpleModal;
使用 State decorator 显示和更新
import React from "react";
import { addDecorator, addParameters } from "@storybook/react";
import { Store, withState } from "@sambego/storybook-state";
const SimpleCounter = props => {
return [
<p> Count: {props.count} </p>,
<button onClick={props.handleCountUpdate}> {props.count} </button>
];
};
const store = new Store({
count: 0,
handleCountUpdate: () => store.set({ count: store.get("count") + 1 })
});
addDecorator(withState());
addParameters({
state: {
store
}
});
export default { title: "Counter" };
export const Simple = () => SimpleCounter;
Store
store 有几个方法可以用来获取和更新状态。
创建新实例时,你可以传递初始状态。
const store = new Store({
foo: "bar",
active: true,
items: ["item 1", "item 2"]
});
你可以使用 get()
方法从 store 中检索状态。
store.get("foo"); // will return 'bar'
store.get("active"); // will return true
store.get("items"); // will return ['item 1', 'item 2']
你可以使用 set()
方法更新 store。
store.set({
active: false,
bar: "foo"
});
你可以使用 subscribe()
方法订阅 store 中的更改。你可以注册一个回调函数,该函数将在状态更新时以更新后的状态作为第一个参数。
store.subscribe(state => // Do something with the updated state.
State 组件
State 组件接受一个属性,即 Store
的实例。所有依赖于状态或应在状态更改时更新的属性都应添加到 Store 中,并由 <State />
组件传播到你的组件。
<State store={store}>
<StateDependendComponent />
</State>
state 还允许将函数作为子项,以便你可以将状态传递给组件的任何 prop。
const store = new Store({
active: true
});
<State store={store}>
{state => [
<ElementOne active={state.active} />,
<ElementTwo checked={state.active} />
]}
</State>;
你还可以通过 parseState 属性在将状态传递给子项之前对其进行操作。
<State store={store} parseState={state => ({ ...state, id: `#${state.uuid}` })}>
<StateDependendComponent />
</State>
使用 withState
decorator 时,你可以将状态解析函数作为参数传递。
addDecorator(withState());
addParameters({
state: {
store,
parseState: state => ({ ...state, count: `foo-${state.count}` })
}
});