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

高阶组件 #14

Open
george-wq opened this issue Sep 25, 2019 · 0 comments
Open

高阶组件 #14

george-wq opened this issue Sep 25, 2019 · 0 comments

Comments

@george-wq
Copy link
Owner

高阶组件

一个高阶组件只是一个包装了另外一个 React 组件的 React 组件。

在介绍高阶组件之前引入一个概念,渲染属性: 它在某种程度上解决了有状态组件的可复用性。

判断一个组件的类型,就是看:该组件是有状态(stateful),还是无状态(stateless)。
同样,如果使用一个组件,需要维护一个内部的状态,那么就选择有状态的组件类型;相反,如果不需要维护状态,就是无状态类型组件。

有状态: 项目目录container
无状态: 项目目录component

import React, { Component } from "react";

class Provider extends Component {
	constructor(props) {
		super(props);
		this.state = {
			name: 'provider-user'
		}
	}
	render() {
    // 执行props传过来的箭头函数,并传入数据
		return this.props.render(this.state.name)
	}
}

class User extends Component {
	render() {
		return (
			<div>
				{this.props.data}
			</div>
		);
	}
}

// 渲染属性 解决有状态组件的可复用问题
// User组件的数据来自 Provider(数据提供器)
class App extends Component {
	render() {
		return (
			<Provider render={(data) => <User data={data}/>}/>
		);
	}
}
export default App

我可以使用高阶组件做什么呢?

概括的讲,高阶组件允许你做:

  • 代码复用,逻辑抽象,抽离底层准备(bootstrap)代码
  • 渲染劫持
  • State 抽象和更改
  • Props 更改

高阶组件工厂的实现

在这节中我们将学习两种主流的在 React 中实现高阶组件的方法:属性代理(Props Proxy)和 反向继承(Inheritance Inversion)。两种方法囊括了几种包装 WrappedComponent 的方法。

https://www.jianshu.com/p/0aae7d4d9bc1

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

No branches or pull requests

1 participant