React 基础面试题, JSX
React 基础面试题, JSX
QA
Step 1
Q:: What is JSX?
A:: JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML directly within React code. JSX produces React elements and it’s syntactic sugar for the React.createElement() function. Although JSX is not mandatory in React, it makes writing UI components more intuitive.
Step 2
Q:: Why is JSX used in React?
A:: JSX makes it easier to write and add HTML in React. It allows developers to combine HTML with JavaScript logic, which enables more readable and maintainable code. Additionally, JSX helps prevent injection attacks since it escapes any values embedded in the JSX expressions.
Step 3
Q:: Can browsers read JSX directly?
A:: No, browsers cannot read JSX directly. JSX needs to be transpiled into regular JavaScript using tools like Babel before it can be executed in the browser.
Step 4
Q:: How do you embed expressions in JSX?
A:: You can embed any JavaScript expression in JSX by wrapping it in curly braces {}. For example, you can include a variable, a function call, or any JavaScript expression inside the JSX code.
Step 5
Q:: What are the limitations of JSX?
A:: JSX expressions must have a single parent element. You cannot return multiple sibling elements directly without wrapping them in a single enclosing tag, like a <div> or <React.Fragment>. Additionally, JSX attributes cannot contain objects and functions directly without using curly braces.