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 createFactory函数 #6

Open
monsterooo opened this issue Apr 1, 2018 · 0 comments
Open

关于React createFactory函数 #6

monsterooo opened this issue Apr 1, 2018 · 0 comments

Comments

@monsterooo
Copy link
Owner

monsterooo commented Apr 1, 2018

官方解释
返回一个函数,这个函数可以产生你给定类型的React元素。像React.createElement(),参数类型可以是div、span、一个React Component(类或函数),或是一个React.fragment

官方说的有点含糊并且也没有提供一些代码示例,下面就来总结一下这两个的使用方法和区别

  • React.createElement()
React.createElement(
  type,
  [props],
  [...children]
)

这个函数用法很明显它创建一个React元素,并且接收三个参数。第一个参数为类型包括html元素类型和React Component或React fragment。第二个参数是元素的属性对应的是html的属性,第三个参数为子元素,可以为一个字符串。也可以是React Component

  • React.createFactory()
React.createFactory(type)

createFactory底层还是调用了createElement,不同的是createFactory返回的是一个函数。它不会立刻调用createElement。而是在你调用这个返回函数的时候创建元素(HOC)

举个例子

const factory = React.createFactory('div');
const TestCreateFactory = factory(null, 'div create factory');

上面factory函数是调用createFactory返回的一个函数,调用factory函数创建的所有组件必然是一个html的div元素,factory(null, 'div create factory')可以为创建的div元素指定属性和子元素。

总结

React.createElement立刻创建一个React组件
React.createFactory返回一个工厂函数,调用它可以创建一系列相同的组件。

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