在 javascript 中,react 组件通过继承 react.component 类来定义。你需要创建一个 es6 类,实现一个返回 jsx 元素的 render 方法,并在构造函数中初始化状态或绑定事件处理函数。

如何正确初始化状态和绑定事件处理函数
在类的构造函数中,必须调用 super(props) 以初始化父类组件,随后通过 this.state = { ... } 设置初始状态。对于事件处理函数,由于 JavaScript 中 this 的指向问题,需要在构造函数中使用 .bind(this) 进行绑定,或者使用箭头函数属性语法。

import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
// 方式一:在构造函数中绑定
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
export default Counter;上述代码展示了一个基础的计数器组件。构造函数中调用了 super(props) 并设置了 count 为 0 的初始状态。点击按钮时,handleClick 被触发,通过 setState 更新状态,导致组件重新渲染。
生命周期方法在类组件中如何使用
类组件提供了明确的生命周期钩子,如 componentDidMount、componentDidUpdate 和 componentWillUnmount。这些方法允许你在组件挂载后、更新后或卸载前执行副作用操作,例如数据获取或清理定时器。

import React from 'react';
class DataFetcher extends React.Component {
constructor(props) {
super(props);
this.state = { data: null, loading: true };
}
componentDidMount() {
// 模拟异步数据获取
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => {
this.setState({ data, loading: false });
})
.catch(err => console.error(err));
}
componentDidUpdate(prevProps) {
if (prevProps.userId !== this.props.userId) {
// 当 userId 变化时重新获取数据
this.setState({ loading: true });
fetch(`https://api.example.com/data/${this.props.userId}`)
.then(res => res.json())
.then(data => this.setState({ data, loading: false }));
}
}
componentWillUnmount() {
// 清理工作,如取消未完成的请求
console.log('Component unmounted');
}
render() {
if (this.state.loading) return <p>Loading...</p>;
return <div>Data: {JSON.stringify(this.state.data)}</div>;
}
}
export default DataFetcher;该示例展示了如何在 componentDidMount 中发起首次请求,并在 componentDidUpdate 中根据 props 变化更新数据。这种模式确保了组件在不同阶段能正确处理外部数据流。
类组件中的状态更新是同步还是异步的
在类组件中,setState 的行为取决于调用上下文。在合成事件和生命周期方法中,它是异步批处理的;但在原生 DOM 事件或 setTimeout 中,它是同步执行的。理解这一点有助于避免在状态更新后立即读取 this.state 导致的陈旧值问题。
import React from 'react';
class AsyncDemo extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
}
handleSyntheticEvent = () => {
this.setState({ value: this.state.value + 1 });
console.log(this.state.value); // 输出 0,因为 setState 是异步批处理的
};
handleNativeEvent = () => {
document.getElementById('native-btn').addEventListener('click', () => {
this.setState({ value: this.state.value + 1 });
console.log(this.state.value); // 输出 1,因为在原生事件中是同步的
});
};
render() {
return (
<div>
<button onClick={this.handleSyntheticEvent}>Synthetic</button>
<button id="native-btn">Native</button>
<p>Current Value: {this.state.value}</p>
</div>
);
}
}
export default AsyncDemo;


















