返回

从“浅尝辄止”到“游刃有余”,React 之三大属性完全解析

前端

React 之三大属性解析

1. State(状态)

State 是一个对象,它包含组件的数据状态,当状态变化时,会触发组件的重新渲染。State 的值可以是任何类型的数据,包括字符串、数字、布尔值、数组和对象。

声明 State:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    // 初始化 State
    this.state = {
      count: 0,
      name: 'John Doe'
    };
  }
}

更新 State:

// 使用 `setState()` 方法更新 State
this.setState({
  count: this.state.count + 1
});

2. Props(属性)

Props 是从组件外部传递进来的属性,它包含了组件需要的数据。Props 是只读的,不能在组件内部修改。

声明 Props:

function MyComponent(props) {
  const { name, age } = props;

  return (
    <div>
      <h1>{name}</h1>
      <p>年龄:{age}</p>
    </div>
  );
}

使用 Props:

<MyComponent name="John Doe" age={30} />

3. Refs(引用)

Refs 是一个指向组件内部某个元素的引用。Refs 可以用于访问 DOM 元素,也可以用于在组件之间传递数据。

声明 Refs:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    // 创建 Ref
    this.myRef = React.createRef();
  }

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

使用 Refs:

// 获取 DOM 元素
const myElement = this.myRef.current;

// 在组件之间传递数据
this.childRef.current.someMethod();

结语

React 之三大属性 State、Props 和 Refs 是构建组件的基础,掌握它们对于理解 React 的工作原理和编写高质量的 React 代码至关重要。通过本文的讲解,相信您已经对 React 之三大属性有了更深入的了解。