agusquiw / react
在Magento中使用React
dev-master
2021-09-19 16:45 UTC
Requires
- php: 7.4.*
- magento/framework: 103.0.*
This package is auto-updated.
Last update: 2024-09-20 00:30:35 UTC
README
可以使用常规JS创建React组件。例如
// File: app/code/Agusquiw/ReactDemo/view/frontend/web/js/components/Counter.js" define(['react', 'html'], ({ useState, useCallback, useEffect }, html) => { const Counter = (props) => { const [count, setCount] = useState(props.initialValue || 0); const decreaseCount = useCallback(() => setCount((count) => count - 1)); const increaseCount = useCallback(() => setCount((count) => count + 1)); return html` <div> <button onClick=${decreaseCount}>Decrease</button> <span>${count}</span> <button onClick=${increaseCount}>Increase</button> </div> `; }; return Counter; });
可以使用自定义小部件reactComponent
将React组件添加到phtml模板中
<div data-mage-init='{ "reactComponent": { "component": "Agusquiw_ReactDemo/js/components/Counter", "props": { "initialValue": 0 } } }' ></div>
这将生成类似以下内容的输出
Htm而不是JSX
为了简化React的使用并避免编译的需要,此扩展使用了htm来实现类似JSX的语法。
自定义钩子
此扩展实现了一些钩子,负责与Magento通信。
useForcedUpdate
通过调用forceUpdate
函数强制更新调用组件。它可以传递给其他组件,甚至可以在任何地方共享。
const forceUpdate = useForcedUpdate();
useObservable
同步React状态与可观察对象。
const [cartData, setCartData, getCartData] = useObservable(customerData.get('cart-data'));
useSharedState
用于在多个React组件之间共享状态的钩子。
const [state, setState, getState] = useSharedState('state', 0);
事件总线
由于多个无关组件将被渲染,它们之间需要一个通信系统。Agusquiw_React/js/eventBus
提供了此类服务。
路线图和待办功能
- 根据Magento Admin配置在react-development和react-production构建之间切换。
- 有用的模板和块,以避免样板代码。
- API查询系统和钩子,类似于apollo graphql,但不一定使用graphql。
贡献
- 使用prettier。
- 不要在代码中添加冗余的注释。
- 不要提前优化。
- 贡献想法也是一种贡献。
演示
演示可以在Agusquiw_ReactDemo找到。