Hello, I am Cangcang Liangliang, a front-end developer. At present, I am publishing some interesting and knowledge about front-end learning on Nuggets, Zhihu and my personal blog. Welcome to follow me.
I prepared to write this article in June last year, but at that time I only used React for more than a month, so I was not so comfortable with many methods of using JSX. After six months of use, I found that JSX could do too many things. And JSX has greater advantages over Vue template syntax in creating reusable components.
Just to be clear: Both Vue and React have their own strengths, and some of this article is for comparison purposes rather than one-upside-down.
1. Create reusable components
The ability to create reusable components is nothing new, and modern front-end frameworks can create reusable components, but in JSX you create components and everything in that component can be easily modified if you want.
When I was creating components when SWITCHING from Vue to React, I checked the React official documentation for a Vue feature: slots.
In Vue, as long as you create components, you need to use slots in most cases, but I looked around in the React documentation for a long time. It seems that there is no such concept in React, and I felt strange at the time, because without it, the reuse of components is not that high when creating components.
After looking into React, I realized that there was no need for slots at all, because the JSX syntax allows for a more powerful way to write, and any Props property can be used as a slot.
If you want to change the icon on a custom component, or change the text to a button, you can think about how to do that in a Vue. Yes, almost the best way to do that is to use slots. What if you wanted to change the names of the bottom two buttons? So if you don’t want these two buttons, want to customize the bottom, or don’t need the bottom at all, what do you do with Vue?
If you need more customization, do you need to use a lot of slots in Vue, even dynamic slots? In JSX, these problems can be easily solved.
Taking a look at the following example, you can imagine how to create this type of component using Vue.
In JSX, there is no such thing as a slot, but it has one more useful feature than a slot. All properties on a component can be inserted into a ReactNode as a slot, which is much simpler and more intuitive than a slot, as shown in the following code.
import React from "react";
interface TestProps {
children: React.ReactNode; buttonRender? : React.ReactNode; }function Test({ buttonRender, children }: TestProps) {
return (
<>
{children}
{buttonRender}
</>
);
}
export default function App() {
return (
<div className="App">
<Test buttonRender={<button>You can pass in the DOM here</button>} > test</Test>
</div>
);
}
Copy the code
The final render looks like this:
Do not underestimate this feature, it is very useful when creating custom components, it can give the user a great deal of customization to use the component, for example, let’s change the above code:
import React from "react";
interface TestProps {
children: React.ReactNode; buttonRender? : React.ReactNode; }function Test({ buttonRender, children }: TestProps) {
return (
<>
{children}
{buttonRender || <button>Here's the default button</button>}
</>
);
}
export default function App() {
return (
<div className="App">
<Test>test</Test>
</div>
);
}
Copy the code
Render result:
In general, you can give a default ReactNode, display the default ReactNode if the user does not pass in the attribute value, and replace the default ReactNode if the attribute value is passed in.
It is important to note that, like Vue slots, a ReactNode rendered by attributes cannot read attributes from child nodes.
In general, any function property of React can be used as a slot, which makes component creation extremely customizable. If you’ve ever used Antd, you’ll notice that Antd is a library of components that you can customize.
2. Use variables and functions
In many cases, we want to convert some values on the page. If you want to use a function provided by a third party library in the Vue template syntax, you need to declare it in data to use it in the template syntax. Let’s take monentJS as an example and do the following:
<template>
<div id="app">
{{ moment().format("h:mm:ss") }}
</div>
</template>
<script>
import moment from "moment";
export default {
name: "App".data() {
return {
// You need to export it in order to use it in the interfacemoment, }; }};</script>
Copy the code
In JSX, you can refer directly to third-party libraries or functions you define elsewhere. Using MonentJS as an example, you can do this directly in JSX:
import moment from "moment";
export default function App() {
return <div className="App">{moment().format("h:mm:ss")}</div>;
}
Copy the code
The use of third-party libraries in template syntax will export more than JSX step steps, and because the Vue of your statement in the data attribute is a two-way binding automatically, can cause some performance problems or other unexpected bugs, of course you can also use the Vue advanced grammar cancel two-way binding, even freeze this property, It’s just a little bit more difficult to operate.
3. Extract any ReactNode
JSX the most flexible place is that you can write any ReactNode in function, for use in the JSX directly, such benefits if you extract into the new component, then comes to the value of the problem, but you, as a function of extraction can directly reference variable has been declared in the current function, may express up more troublesome, So let’s just look at the following example:
import { useState } from "react";
export default function App() {
const [title, setTitle] = useState("Hello world!");
// ReactNode can be extracted here
const show = <h1>{title}</h1>;
return (
<div className="App">{/* use */} {show}<button
onClick={()= >{setTitle(" can also change "); I}} ></button>
</div>
);
}
Copy the code
The code above should look like this:
This feature of JSX allows you to create a lot of operations, and it can be used in conjunction with useMemo, which I sometimes use when writing projects, such as the following
import { useMemo, useState } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
const show = useMemo(() = > {
if (count === 0) return <div>Hello World!</div>;
return (
<img
src="https://pic.qqtn.com/up/2019-9/15690311636958128.jpg"
alt="Image"
/>
);
}, [count]);
return (
<div className="App">
{show}
<button
onClick={()= >{ setCount(1); I}} ></button>
</div>
);
}
Copy the code
The code above is rendered to look like this:
4. Recursive components
One of the biggest benefits of using JSX is recursive components. It is almost impossible to write recursive components in Vue template syntax, but it is not impossible to write recursive components using Vue.
{% post_link React/React: {% post_link React/React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React: {% post_link React:}}
5. Unlock the JS whole
In Vue, if you use template syntax, you will be limited by the Vue version, and you will not be able to use some of the new JS syntax in template syntax, such as Vue2. This is a very useful syntax, but in JSX, as long as your Babel is new, JSX supports all JavaScript syntax, such as this syntax:
I highly recommend? Its Chinese name is the optional chain operator. In ES11, it is officially included in the specification. Let’s first look at the following code:
const data = {
name: "Zhang".age: 18.sex: "Male"
};
console.log(data.friend.name); TypeError: Cannot read property 'name' of undefined
Copy the code
So we have to make a lot of judgments at this point.
const data = {
name: "Zhang".age: 18.sex: "Male"
};
console.log(data && data.friend && data.friend.name); // undefined
Copy the code
With the optional chain operator (? .). After, we can directly write as:
const data = {
name: "Zhang".age: 18.sex: "Male"
};
console.log(data? .friend?.name);Copy the code
As you can see, the code is much simpler.
, you might think, much of it, in fact, this feature is very useful, especially when the data from the backend access, because the backend access to data, you don’t know the backend will return to undefined, if return is undefined, the front-end when invoked, Vue may appear white interface, React may cause interface errors.
Let’s use the above code in Vue:
<template>
<div>Here is the test: {{data? .friend?.name }}</div>
</template>
<script>
export default {
name: "App".data() {
return {
data: {
name: "Zhang".age: 18.sex: "Male",}}; }};</script>
Copy the code
Attention! The above code will report a syntax error in Vue2:
Vue3 allows normal parsing:
As an added bonus, Vue3 is better off using new syntax, because the Composition API is similar to the React Hooks, and the experience is great!
<template>
<div>Here is the test: {{data? .name }}</div>
</template>
<script>
import { reactive } from "vue";
export default {
name: "App".setup() {
const data = reactive({ name: "Zhang".age: 18.sex: "Male" });
return{ data, }; }};</script>
Copy the code
We’ll use the above code in React:
const data = { name: "Zhang".age: 18.sex: "Male" };
export default function App() {
return <div>Here is the test: {data? .friend?.name}</div>;
}
Copy the code
6. Perfect with TS
In Vue, support for TypeScript is a big problem because of the template syntax. For example, declaring properties in data is not a good way to give them types. Vue-class-component comes out and then someone wraps it around and releases vue-property-decorator, but it still doesn’t solve the TypeScript/VUE mismatch perfectly.
JSX combines TypeScript perfectly to become TSX. TSX has more maintainable features, such as generic components, as shown in this article: {% post_link React/TS: Generic components %}
React doesn’t have any of these problems, and JSX works perfectly with TypeScript to get all of TypeScript’s capabilities.
Again, with optional chains, let’s look at the differences between JSX and TSX.
JSX has a hint but no error:
TSX has syntax hints and error messages:
7. The last
React also provides some advanced syntax for creating components. Although it may not be used in business code, it may be used a lot when creating components. Personally, I rarely write components, but the Antd source code uses this advanced syntax extensively. I’ll probably dig deeper into these usages later.
Once you get used to JSX, you’ll find that JSX is a fantastic way to write, as if you can create complex components that are informative, so whether you use React or not, JSX is recommended, and JSX parsing is now built into TypeScript.
And even if you use Vue, you can create more complex components using JSX syntax in Vue by using the corresponding bable usage.