An overview of the
When we used React, we needed React. CreateElement to create a virtual DOM, which made the code look complicated. Can it be as simple as Vue?
Use the JSX. X stands for extension, so JSX is an extended version of JS. Using JSX syntax allows you to simplify your code and achieve the same effect.
Vue has a vue-loader ->. Vue file to write
React uses jSX-loader. Jsx-loader is actually replaced by Babel-loader, which is built into Webpack.
Use the JSX
-
Method 1: CDN (never use in production environment, it is too inefficient (introduction + translation))
- The introduction of babelmin. Js
- the
<script>
to<script type="text/babel">
- Babel will automatically translate, for example
- This approach does not seem to support SRC
-
Method 2: webpack+babel-loader (novice skip)
-
Method 3: Use create-react-app
The easiest way to do this is to use the Create React app
We’ve already used it to create a React project, and its usage is similar to @vue/cli. Install globally first, then create the project, CD into the project. Develop using YARN start.
Let’s start with a React function component, app.js
import React from "react"; Const App = () => {return (<div> I am App component </div>;) }; export default App;Copy the code
Note that this is a JS file. It is illegal to write HTML in JS. But why is it ok here? This is because create-react-app automatically treats JS as JSX. JSX syntax is that App is a function and returns an element. It can be written as an HTML tag without the hassle of react.createElement (). Include content or child elements directly inside.
So this
//index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App.js";
ReactDOM.render(<App />, document.getElementById("root"));
Copy the code
We then introduce the App component in index.js and render it using ReactDOM. We can call the function App() here, but more often we render it as a component, written as
Considerations for using JSX
-
ClassName If you want to write a class attribute, say className
because it will be translated as react. createElement(‘div’,{className:’red’})
-
Insert variables and functions are wrapped in {}, and all JS code in the tag is wrapped in {}.
For example, {n} represents variable n; If you want to represent an object, you also wrap the object with {}, as in {{name:’li’}}.
-
In a component, it is customary to add a () after the return to wrap things inside.
conclusion
React JSX is similar to vuE-loader in Vue. Vue-loader can convert three tags in a. Vue file into construction options.
JSX can also be written directly as a tag, equivalent to react.createElement (). Jsx-loader is integrated into babel-loader, which is built into Webpack, so.js files use JSX syntax by default.