如何使用react组件
创建React组件
React组件可以通过函数或类的方式创建。函数组件适用于简单的UI展示,类组件适用于需要状态管理和生命周期方法的场景。
函数组件示例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件props的使用
props是组件之间传递数据的主要方式。父组件通过属性传递数据,子组件通过props接收。
父组件传递props:
<Welcome name="Alice" />
子组件接收props:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
组件状态管理
类组件可以使用state来管理内部状态。通过setState方法更新状态会触发组件重新渲染。
初始化state:

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}
更新state:
this.setState({ count: this.state.count + 1 });
生命周期方法
类组件提供生命周期方法,可以在不同阶段执行代码。常用的生命周期方法包括componentDidMount、componentDidUpdate和componentWillUnmount。
组件挂载后执行:
componentDidMount() {
// 执行初始化操作
}
组件更新后执行:

componentDidUpdate(prevProps, prevState) {
// 响应props或state变化
}
事件处理
React事件处理采用驼峰命名法,需要显式绑定this或使用箭头函数。
显式绑定this:
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Button clicked');
}
}
箭头函数方式:
handleClick = () => {
console.log('Button clicked');
}
组件组合
通过组合多个简单组件可以构建复杂UI。使用children prop可以创建包含其他组件的容器组件。
容器组件示例:
function Card(props) {
return (
<div className="card">
{props.children}
</div>
);
}
// 使用方式
<Card>
<h2>Title</h2>
<p>Content</p>
</Card>






