任何人都知道这一行中的 null
是什么:
React.DOM.p(null, message);
我知道它是 createElement
的便利包装器,即
ReactElement createElement(
string/ReactClass type,
[object props],
[children ...]
)
但我很难理解为什么 type
是 null
。
这里的这一行也是如此:
React.DOM.div(null, 'Hello World!')
最佳答案
这些函数通常称为 factories这意味着它们是生成具有特定类型属性的 ReactElements
的函数。
这些工厂大致是这样创建的:
function createFactory(type) {
return React.createElement.bind(null, type);
}
返回 React.createElement
作为绑定(bind)函数,this
绑定(bind)到 null
和 type
绑定(bind)到任何被传入,允许你为你的元素创建速记实例化函数:
// create a function that creates React <div> elements
let div = createFactory('div');
// create two divs using the div factory function
let div1 = div({ /* some props */ }, 'Div 1');
let div2 = div({ /* some props */ }, 'Div 2');
React 已经为常见的 HTML 标签提供了内置工厂,例如 div
、li
等,您在问题中有这些标签。
but am struggling to understand why the type is null.
考虑到以上所有内容,当您查看其中一个示例时:
React.DOM.div(null, 'Hello World!')
发生以下情况:
React.DOM.div
只是一个工厂函数,它在后台将 'div'
作为第一个参数传递给 React.createElement
,这是类型,其他所有内容都作为剩余参数传递。
基本思路:
// the function is created as a factory
React.DOM.div = createFactory('div');
// and used to create a <div> element
var myDiv = React.DOM.div(null, 'Hello World');
div
的值作为第一个参数的设置方式与我在创建该工厂时在上面显示的方式类似。
因此,null
在您的例子中只是 props
对象,而不是 type
。类型通过工厂绑定(bind)为 div
,这意味着 props
是第一个参数,'Hello World!'
string 是 children
参数。
关于javascript - React.DOM.p(null, message) - 解释null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38229959/