返回

React 入门学习(二)—— 面向组件编程之属性props、state、ref

前端

在上一篇文章中,我们了解了 React 的基本概念和组件的概念。在本文中,我们将深入探讨 React 中的三大属性:props、state 和 ref,它们是实现组件式编程的关键。让我们深入了解这些属性的用法和功能,并通过示例代码演示如何有效地利用它们来构建出色的 React 组件。


1. props

props 是 component component 的简称,它指的是组件的属性。props 用来将父组件的数据传递给子组件。props 是只读的,这意味着子组件不能改变父组件传递过来的数据。 props 的传递过程是单向的,即父组件可以向子组件传递数据,而子组件不能向父组件传递数据。如果子组件需要向父组件传递数据,可以使用事件处理函数。

2. state

state 是组件的状态。state 用于存储组件内部的数据。state 是可变的,这意味着组件可以改变 state 中的数据。 state 的更新过程是异步的,即当组件调用 setState() 方法更新 state 时,state 不会立即更新。而是会被添加到一个队列中,然后在稍后由 React 更新。这种异步更新机制可以提高 React 的性能。

3. ref

ref 是组件的引用。ref 用于获取组件的 DOM 节点。ref 是可变的,这意味着组件可以改变 ref 的值。 ref 的用法主要有两种: 一种是使用回调函数获取 DOM 节点,另一种是使用 useRef() 钩子获取 DOM 节点。回调函数获取 DOM 节点的方式如下: ```javascript class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = null; }

render() {
return <div ref={(ref) => { this.myRef = ref; }} />;
}
}

useRef() 钩子获取 DOM 节点的方式如下:
```javascript
import { useRef } from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = useRef(null);
  }

  render() {
    return <div ref={this.myRef} />;
  }
}

ref 的主要作用是操作 DOM 节点。例如,我们可以使用 ref 来获取组件的 DOM 节点,然后对 DOM 节点进行操作,比如:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = null;
  }

  render() {
    return <div ref={(ref) => { this.myRef = ref; }} />;
  }

  componentDidMount() {
    this.myRef.current.style.color = 'red';
  }
}

在上面的代码中,我们使用 ref 获取了组件的 DOM 节点,然后在 componentDidMount() 生命周期函数中将 DOM 节点的颜色设置为红色。


总结

props、state 和 ref 是 React 中的三大属性。props 用于将父组件的数据传递给子组件。state 用于存储组件内部的数据。ref 用于获取组件的 DOM 节点。这三个属性是实现组件式编程的关键。通过熟练掌握这些属性,我们可以构建出出色的 React 组件。 我希望这篇文章对您有所帮助。如果您有任何问题,请随时告诉我。我将尽力帮助您。