一、React 的三大核心特点是什么?
- 声明式编程 :通过JSX描述UI最终状态,开发者无需操作DOM细节(如
<div>{count}</div>
); - 组件化:将UI拆分为独立可复用的组件(如函数组件、类组件);
- 一次学习,多端编写:支持Web、Native(React Native)、SSR等场景。
二、React 中如何实现条件渲染?
- JS表达式:在JSX中直接使用逻辑运算符
javascript
{isLoggedIn && <UserPanel />}
- 变量存储元素:
ini
let message = null;
if (error) message = <ErrorBox />;
return <div>{message}</div>;
- 三元运算符:
javascript
{score > 60 ? <Pass /> : <Fail />}
三、什么是 React 的合成事件(SyntheticEvent)?
React 封装浏览器原生事件,提供跨浏览器一致的事件对象。
特点:
- 事件委托:所有事件冒泡到顶层
document
处理,提升性能; - 自动回收:事件对象在回调结束后会被清除,需用
e.persist()
手动保留; - 统一API:如
onClick
对应click
事件,onChange
统一处理表单输入。
四、如何用 PropTypes 进行类型检查?
- 安装
prop-types
库; - 在类组件中定义静态属性:
scala
import PropTypes from 'prop-types';
class Button extends React.Component {
static propTypes = {
color: PropTypes.oneOf(['red', 'blue']).isRequired,
onClick: PropTypes.func
};
}
- 函数组件中使用:
css
function Button({ color }) { ... }
Button.propTypes = { color: PropTypes.string };
五、React 组件是什么?
React 组件是一个接收props
(输入参数)并返回描述UI的React元素(输出)的函数或类。
scala
// 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// 类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
六、React.Fragment 的作用是什么?
用于包裹多个子元素而不添加额外DOM节点:
javascript
function Table() {
return (
<React.Fragment>
<td>Cell 1</td>
<td>Cell 2</td>
</React.Fragment>
);
}
// 简写语法:
<>
<td>Cell 1</td>
<td>Cell 2</td>
</>
七、React Hooks 的使用规则有哪些?
- 顶层调用:只能在函数组件的最外层或自定义Hook中使用,不可嵌套在条件/循环中;
- 仅React函数调用:只能在React组件函数或自定义Hook中调用;
- 命名规范 :自定义Hook必须以
use
开头(如useToggle
)。
八、如何阻止组件渲染?
在组件中返回null
,不会触发生命周期方法(如componentDidUpdate
):
javascript
function Banner({ shouldShow }) {
if (!shouldShow) return null; // 阻止渲染
return <div>Special Offer!</div>;
}
九、如何设置组件默认的props值?
通过defaultProps
静态属性:
matlab
function Button({ size }) { ... }
Button.defaultProps = {
size: 'medium' // 未传递size时默认值为'medium'
};
十、React 元素(Element)和组件(Component)有什么区别?
- 元素 :普通JS对象,描述DOM节点及其属性,如
<div className="test" />
会被编译为:
css
{ type: 'div', props: { className: 'test' }, children: null }
- 组件:接收props并返回元素的函数或类,可包含逻辑和状态管理。