React 组件

React组件知识点大全

React 组件知识点大全

编程小白也能看懂的详细指南

1. 组件是什么?

组件就像乐高积木,是React应用的构建块。每个组件负责UI的一部分,可以独立开发、测试和复用。

组件有两种类型:函数组件类组件

2. 函数组件

最简单的组件形式,就是一个JavaScript函数,返回JSX(描述UI的语法)。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

特点:简单、无状态(现在有Hooks可以解决)

3. 类组件

使用ES6类的形式创建,可以拥有状态生命周期方法

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

4. Props(属性)

组件之间传递数据的方式,从父组件流向子组件(单向数据流)。

Props是只读的,组件不能修改自己的props。

// 父组件传递name属性
<Welcome name=”小明” />

// 子组件接收props
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

5. State(状态)

组件内部的数据存储,状态改变会触发组件重新渲染。

类组件使用this.statethis.setState()

函数组件使用useState Hook

// 类组件状态示例
class Counter extends React.Component {
  state = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <button onClick={this.increment}>
        Clicked {this.state.count} times
      </button>
    );
  }
}

6. 生命周期方法(类组件)

组件从创建到销毁经历的不同阶段:

  • 挂载阶段:componentDidMount()
  • 更新阶段:componentDidUpdate()
  • 卸载阶段:componentWillUnmount()

函数组件使用useEffect Hook来替代

7. Hooks(函数组件的超能力)

让函数组件也能使用状态和其他React特性:

  • useState:管理状态
  • useEffect:执行副作用(数据获取、订阅等)
  • useContext:使用上下文
  • useRef:访问DOM或保存可变值
  • 还有更多:useReducer, useCallback, useMemo等

8. 事件处理

React事件使用驼峰命名法(如onClick),而不是全小写。

需要传递函数作为事件处理函数,而不是字符串。

function ActionButton() {
  const handleClick = () => {
    alert(‘按钮被点击了!’);
  };

  return (
    <button onClick={handleClick}>
      点击我
    </button>
  );
}

9. 条件渲染

根据条件显示不同内容:

  • if/else语句
  • 三元运算符 condition ? true : false
  • 逻辑与运算符 &&
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>欢迎回来!</h1>;
  }
  return <h1>请先登录</h1>;
}

10. 列表渲染

使用map()方法渲染列表,每个子元素必须有唯一的key属性。

function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map((number) =>
        <li key={number.id}>{number.value}</li>
      )}
    </ul>
  );
}

key帮助React识别哪些元素改变了(增加、删除、重排)

11. 组件组合

通过props.children实现组件嵌套:

function Card(props) {
  return (
    <div className=”card”>
      {props.children}
    </div>
  );
}

// 使用Card组件
<Card>
  <h1>标题</h1>
  <p>内容…</p>
</Card>

12. Context API

在组件树中跨层级传递数据,避免层层传递props。

使用场景:用户认证、主题、语言偏好等全局数据。

// 创建Context
const ThemeContext = React.createContext(‘light’);

// 提供Context值
<ThemeContext.Provider value=”dark”>
  <App />
</ThemeContext.Provider>

// 消费Context值
const theme = useContext(ThemeContext);

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部