乐闻世界logo
搜索文章和话题

How to use mobx-react ' observer ' without decorator syntax?

1个答案

1

When using MobX with React in environments that do not support decorator syntax, we can directly convert React components into reactive components using the observer function. This approach avoids decorator syntax entirely and instead employs a function wrapper. The main steps are as follows:

  1. Import necessary modules: First, import the observer function from the mobx-react package.
javascript
import { observer } from 'mobx-react';
  1. Create a React component: Define a standard React component.
javascript
import React from 'react'; function TodoView({ todo }) { return ( <div> <input type="checkbox" checked={todo.finished} onChange={() => todo.toggle()} /> {todo.title} </div> ); }
  1. Use the observer function: Wrap your React component with the observer function to make it reactive. This ensures the component automatically re-renders when observed data changes.
javascript
const ObservableTodoView = observer(TodoView);
  1. Use the component: Integrate the converted component into your application.
javascript
import ReactDOM from 'react-dom'; import { observable } from 'mobx'; const todo = observable({ title: "Learn MobX", finished: false, toggle() { this.finished = !this.finished; } }); ReactDOM.render(<ObservableTodoView todo={todo} />, document.getElementById('app'));

In the above example, the TodoView component is converted into a MobX reactive component via the observer function. Consequently, when the finished property of the todo object changes, the TodoView component automatically re-renders to reflect the updated state.

This approach is straightforward and applicable to JavaScript environments without decorator support, such as the default configuration of Create React App. It not only maintains code clarity and manageability but also leverages MobX's reactive programming benefits.

2024年8月16日 00:18 回复

你的答案