React基础 | 青训营笔记

64 阅读3分钟

Snipaste_2023-05-13_22-41-04.png React是一个用于构建用户界面的JavaScript库。它由Facebook开发,并且已经成为创建高效、可扩展和易于维护的Web应用程序的首选框架之一。

下面是一些React基础与实践的笔记:

JSX

JSX是一种将HTML和JavaScript混合的语法扩展。它使得在JavaScript中编写UI变得更加直观和自然。

在React中,可以使用JSX来描述组件的UI结构。例如:

jsxCopy Code
function App() {
  return (
    <div>
      <h1>Hello React!</h1>
      <p>This is a paragraph.</p>
    </div>
  )
}

在上面的例子中,我们定义了一个名为App的函数组件,并返回一个包含<h1><p>元素的<div>元素。这段代码使用了JSX语法来定义UI结构并在JavaScript中返回。

组件

React中的组件是一种独立的可复用代码单元,它封装了UI元素和行为。每个组件都有自己的状态和属性。

您可以使用函数组件或类组件来定义组件。例如:

jsxCopy Code
// 使用函数组件定义组件
function MyComponent(props) {
  return <h1>Hello {props.name}!</h1>
}

// 使用类组件定义组件
class MyComponent extends React.Component {
  render() {
    return <h1>Hello {this.props.name}!</h1>
  }
}

在上面的例子中,我们定义了一个名为MyComponent的组件,并传递了一个name属性。在函数组件中,我们使用props参数来接收传递给组件的属性。在类组件中,我们可以通过this.props来访问属性。

状态

React中的状态(state)是一种特殊的数据,它用于保存组件的数据。当组件的状态发生变化时,React会自动重新渲染组件,以反映更新后的状态。

要使用状态,您需要先定义一个初始状态并将其存储在组件中。然后,您可以使用setState方法来更新组件的状态。例如:

jsxCopy Code
class Counter extends React.Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
      </div>
    )
  }
}

在上面的例子中,我们定义了一个名为Counter的类组件,并将count状态初始化为0。在组件的UI中,我们使用{this.state.count}来显示当前计数器的值。当用户单击“Increment”按钮时,我们调用setState方法来更新count状态。

生命周期

React组件在其生命周期中会经历多个阶段,从而允许开发人员在不同阶段执行不同的操作。React提供了一组钩子函数(hooks),用于在组件生命周期的特定阶段执行代码。

例如,componentDidMount钩子函数会在组件挂载到DOM后立即调用,因此它是执行异步加载数据等操作的理想场所。另外,componentDidUpdate钩子函数会在组件更新后调用,因此它对于执行DOM操作非常有用。

jsxCopy Code
class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { data: null }
  }

  async componentDidMount() {
    const response = await fetch('https://api.example.com/data')
    const data = await response.json()
    this.setState({ data })
  }

  render() {
    if (!this.state.data) {
      return <div>Loading...</div>
    }
    return <div>Data: {this.state.data}</div>
  }
}

在上面的例子中,我们定义了一个名为MyComponent的类组件,并使用componentDidMount钩子函数来从服务器获取数据。在数据加载完成后,我们使用setState方法将其存储在组件状态中。在render方法中,我们根据数据状态显示不同的UI。