Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 组件及其他类型组件 #109

Open
yangtao2o opened this issue Apr 14, 2020 · 0 comments
Open

React 组件及其他类型组件 #109

yangtao2o opened this issue Apr 14, 2020 · 0 comments

Comments

@yangtao2o
Copy link
Owner

组件和不同类型

React 中一切都是组件。 我们通常将应用程序的整个逻辑分解为小的单个部分。 我们将每个单独的部分称为组件。 通常,组件是一个 javascript 函数,它接受输入,处理它并返回在 UI 中呈现的 React 元素。

函数/无状态/展示组件

函数或无状态组件是一个纯函数,它可接受接受参数,并返回 react 元素。这些都是没有任何副作用的纯函数。这些组件没有状态或生命周期方法,比如:

import React from "react";

export const Header = () => {
  return (
    <div style={{ backgroundColor: "orange" }}>
      <h1>TODO App</h1>
    </div>
  );
};

类/有状态组件

类或有状态组件具有状态和生命周期方可能通过setState()方法更改组件的状态。类组件是通过扩展 React 创建的。它在构造函数中初始化,也可能有子组件,比如:

import React from "react";

export class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div style={{ backgroundColor: "orange" }}>
        <h1>TODO App</h1>
      </div>
    );
  }
}

受控组件与非受控组件

  • 受控组件

受控组件是在 React 中处理输入表单的一种技术。表单元素通常维护它们自己的状态,而 react 则在组件的状态属性中维护状态。我们可以将两者结合起来控制输入表单。这称为受控组件。因此,在受控组件表单中,数据由 React 组件处理。

  • 非受控组件

在非受控组件中,Ref 用于直接从 DOM 访问表单值,而不是事件处理程序。

我们使用 Ref 构建了相同的表单,而不是使用 React 状态。使用React.createRef()定义 Ref 并传递该输入表单,并直接从 handleSubmit 方法中的 this.input.current.value 访问表单值。

import React from "react";

export default class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: "Hi" };
    this.input = React.createRef();
  }

  handleSubmit(e) {
    this.setState({
      value: this.input.current.value
    });
    e.preventDefault();
  }

  render() {
    return (
      <>
        <input ref={this.input} onChange={e => this.handleSubmit(e)} />
        <p>{this.state.value}</p>
      </>
    );
  }
}

总结:

受控组件 非受控组件
1. 没有维持自己的状态 1. 保持着自己的状态
2.数据由父组件控制 2.数据由 DOM 控制
3. 通过 props 获取当前值,然后通过回调通知更改 3. Refs 用于获取其当前值

容器组件

容器组件是处理获取数据、订阅 redux 存储等的组件。它们包含展示组件和其他容器组件,但是里面从来没有 html。

高阶组件

高阶组件是将组件作为参数并生成另一个组件的组件。 Redux connect 是高阶组件的示例。 这是一种用于生成可重用组件的强大技术。

学习资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant