Home >Web Front-end >JS Tutorial >How to combine React with mobx? Detailed explanation of react combined with mobx (with examples)

How to combine React with mobx? Detailed explanation of react combined with mobx (with examples)

寻∝梦
寻∝梦Original
2018-09-11 14:44:182177browse

This article mainly introduces the detailed explanation of react combined with mobx. Interested students can discuss it together below. Let's take a look at this article

1. npm install mobx mobx-react --save

2. npm install babel-plugin-transform-decorators-legacy -- save-dev

3. Configure

"babel": {
"presets": [
"react-app"
],
"plugins": [ 
["transform-decorators-legacy"]       
]
}

in package.json 4. Create Store.js

import {observable, action, useStrict} from 'mobx';
useStrict(true);
class Store {
@observable num = 1;
@action plus(){
this.num ++;
}
@action minus(){
this.num --;
}
}
export default Store;

5. Add Store

import {Provider} from 'mobx-react';
import Store from './utils/Store';
const store = new Store();
ReactDOM.render(
<Provider store={store}>
<Routes/>
</Provider>,
document.getElementById(&#39;root&#39;));
# to index.js ##6. Use status in Main.js (if you want to know more, go to the PHP Chinese website

React Reference Manual column to learn)

import {observer,inject} from &#39;mobx-react&#39;;
@inject("store") @observer
class Main extends Component {
render() {
let {num} = this.props.store;
 return <p>
<p>{num}</p>
<button onClick={()=>{this.props.store.plus()}}>加1</button>
<button onClick={()=>{this.props.store.minus()}}>减1</button>
</p>
}
}

7. Realize the effect

How to combine React with mobx? Detailed explanation of react combined with mobx (with examples)

After clicking "Add 1", it becomes

How to combine React with mobx? Detailed explanation of react combined with mobx (with examples)

to implement the counter function.

This article ends here (if you want to see more, go to the PHP Chinese website

React User Manual column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of How to combine React with mobx? Detailed explanation of react combined with mobx (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn