在 React 中,render() 方法是类组件的核心方法,它的主要目的是描述组件应该渲染什么内容到界面上。
一、render() 的主要作用
1. 返回 JSX
render() 方法必须返回一个 React 元素,通常是 JSX:
scala
class MyComponent extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
2. 基于 state 和 props 动态渲染
render() 可以根据组件的状态和属性动态决定渲染内容:
scala
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
3. 条件渲染
根据条件显示不同的 UI:
scala
class UserGreeting extends React.Component {
render() {
const { isLoggedIn, username } = this.props;
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, {username}!</h1>
) : (
<h1>Please log in</h1>
)}
</div>
);
}
}
二、render() 的特点
1. 纯函数
render() 应该是纯函数:
- 不修改组件状态
- 不直接与浏览器交互
- 相同的 props 和 state 总是返回相同的结果
2. 必需的方法
在类组件中,render() 是必须实现的方法(除了使用 React.PureComponent 的情况)。
3. 被 React 调用
开发者不直接调用 render(),React 在以下情况会自动调用:
- 组件初始化时
- state 更新时
- props 更新时
- 父组件重新渲染时
三、函数组件的对应概念
在函数组件中,没有明确的 render() 方法,整个函数就相当于 render():
scala
// 函数组件 - 整个函数就是 render
function MyComponent(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 等同于类组件的 render()
class MyComponent extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}