React 核心概念

组件 (Components)

函数组件

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
 
// 箭头函数写法
const Welcome = (props) => {
  return <h1>Hello, {props.name}</h1>;
};

类组件

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

JSX 语法

基本语法

// 表达式
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
 
// 属性
const element = <div tabIndex="0"></div>;
const element = <img src={user.avatarUrl}></img>;
 
// 子元素
const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

条件渲染

// if 语句
function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}
 
// 三元运算符
function Greeting(props) {
  return (
    <div>
      {props.isLoggedIn ? <UserGreeting /> : <GuestGreeting />}
    </div>
  );
}
 
// 逻辑与运算符
function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

列表渲染

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

Props (属性)

基本使用

// 传递 props
function App() {
  return <Welcome name="Sara" age={25} />;
}
 
// 接收 props
function Welcome(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You are {props.age} years old.</p>
    </div>
  );
}
 
// 解构 props
function Welcome({ name, age }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
    </div>
  );
}

默认 Props

function Welcome({ name, age = 18 }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
    </div>
  );
}
 
// 或使用 defaultProps
Welcome.defaultProps = {
  age: 18
};

State (状态)

useState Hook

import React, { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

复杂状态管理

function Form() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    age: 0
  });
 
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
 
  return (
    <form>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />
    </form>
  );
}

事件处理

基本事件处理

function Button() {
  const handleClick = () => {
    alert('Button clicked!');
  };
 
  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

事件对象

function Form() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted');
  };
 
  const handleChange = (e) => {
    console.log('Input value:', e.target.value);
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

传递参数

function List() {
  const items = ['Apple', 'Banana', 'Orange'];
 
  const handleClick = (item) => {
    console.log('Clicked:', item);
  };
 
  return (
    <ul>
      {items.map(item => (
        <li key={item}>
          <button onClick={() => handleClick(item)}>
            {item}
          </button>
        </li>
      ))}
    </ul>
  );
}

生命周期

useEffect Hook

import React, { useState, useEffect } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  // 组件挂载和更新时执行
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
 
  // 只在挂载时执行
  useEffect(() => {
    console.log('Component mounted');
  }, []);
 
  // 依赖项变化时执行
  useEffect(() => {
    console.log('Count changed:', count);
  }, [count]);
 
  // 清理函数
  useEffect(() => {
    const timer = setInterval(() => {
      console.log('Timer tick');
    }, 1000);
 
    return () => {
      clearInterval(timer);
    };
  }, []);
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

表单处理

受控组件

function NameForm() {
  const [value, setValue] = useState('');
 
  const handleChange = (e) => {
    setValue(e.target.value);
  };
 
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('A name was submitted: ' + value);
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

非受控组件

function NameForm() {
  const inputRef = useRef(null);
 
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('A name was submitted: ' + inputRef.current.value);
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

组件通信

父子组件通信

// 父组件
function Parent() {
  const [message, setMessage] = useState('Hello from parent');
 
  const handleChildClick = (data) => {
    console.log('Data from child:', data);
  };
 
  return (
    <div>
      <Child 
        message={message} 
        onChildClick={handleChildClick}
      />
    </div>
  );
}
 
// 子组件
function Child({ message, onChildClick }) {
  const handleClick = () => {
    onChildClick('Hello from child');
  };
 
  return (
    <div>
      <p>{message}</p>
      <button onClick={handleClick}>Send to parent</button>
    </div>
  );
}

兄弟组件通信

// 通过父组件传递
function Parent() {
  const [sharedData, setSharedData] = useState('');
 
  return (
    <div>
      <Child1 
        data={sharedData} 
        onDataChange={setSharedData}
      />
      <Child2 data={sharedData} />
    </div>
  );
}

性能优化

React.memo

const MyComponent = React.memo(function MyComponent({ name }) {
  return <div>{name}</div>;
});

useMemo

function ExpensiveComponent({ items }) {
  const expensiveValue = useMemo(() => {
    return items.reduce((sum, item) => sum + item.value, 0);
  }, [items]);
 
  return <div>{expensiveValue}</div>;
}

useCallback

function Parent() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');
 
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);
 
  return (
    <div>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <Child onClick={handleClick} />
    </div>
  );
}

错误边界

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
 
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
 
  componentDidCatch(error, errorInfo) {
    console.log('Error caught:', error, errorInfo);
  }
 
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
 
    return this.props.children;
  }
}
 
// 使用
function App() {
  return (
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
  );
}

标签

React 核心概念 组件 JSX Hooks 状态管理