1、作用:
创建React组件实例。
2、实现:
只需创建一个带type参数的createElement的绑定函数即可。
React.createFactory = function(type) {
var factory = React.createElement.bind(null, type);
return factory;
};
参数:可以是html标签字符串,也可以是React.createClass创建的ReactClass对象。
返回值:类似于 React.createElement(),返回一个给定类型的ReactElement元素。
1) type参数是html标签字符串
eg1:
var li1 = React.createElement('li', null, 'First');
var li2 = React.createElement('li', null, 'Second');
var li3 = React.createElement('li', null, 'Third');
var ul = React.createElement('ul', {className: 'list'}, li1, li2, li3);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
eg2:通过createFactory来生成li标签:
var factory = React.createFactory("li");
var li1 = factory(null, 'First');
var li2 = factory(null, 'Second');
var li3 = factory(null, 'Third');
var ul = React.createElement('ul', {className: 'list'}, li1, li2, li3);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
eg3:通过createFactory来生成ul标签:
var factoryLI = React.createFactory("li");
var li1 = factoryLI(null, 'First');
var li2 = factoryLI(null, 'Second');
var li3 = factoryLI(null, 'Third');
var factoryUL = React.createFactory("ul");
var ul = factoryUL({className: 'list'}, li1, li2, li3);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
该例子中只有创建一次ul,因此可以通过createElement来创建即可,当然也可以生成一个ul的工厂方法用于生成ul元素。
eg4:通过React为HTML标签提供的内置的工厂方法 React.DOM.*来生成ul标签:
var factoryLI = React.createFactory("li");
var li1 = factoryLI(null, 'First');
var li2 = factoryLI(null, 'Second');
var li3 = factoryLI(null, 'Third');
var ul = React.DOM.ul({className: 'list'}, li1, li2, li3);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
eg5:通过React为HTML标签提供的内置的工厂方法 React.DOM.*来生成li标签:
var ul = React.DOM.ul(
{className: 'list'},
React.DOM.li(null, 'First'),
React.DOM.li(null, 'Second'),
React.DOM.li(null, 'Third')
);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
2) type参数是ReactClass元素
eg6:
var Li = React.createClass({
render:function(){
return (
<li>{this.props.text}</li>
);
}
})
var li1 = React.createElement(Li, {key:'1',text:'First'});
var li2 = React.createElement(Li, {key:'2',text:'Second'});
var li3 = React.createElement(Li, {key:'3',text:'Third'});
var ul = React.createElement('ul', {className: 'list'}, [li1, li2, li3]);
ReactDOM.render(
ul,
document.getElementById('content')
);
eg7:通过createFactory来生成Li组件,通过React为HTML标签提供的内置的工厂方法 React.DOM.*来生成ul组件:
var Li = React.createClass({
render:function(){
return (
<li>{this.props.text}</li>
);
}
})
var factory = React.createFactory(Li);
var li1 = factory({key:'1',text:'First'});
var li2 = factory({key:'2',text:'Second'});
var li3 = factory({key:'3',text:'Third'});
var ul = React.DOM.ul({className: 'list'}, [li1, li2, li3]);
ReactDOM.render(
ul,
document.getElementById('timeBox')
);
当然,同样也可以通过createFactory来生成Ul组件,这与type参数是html标签字符串时类似,不做重复说明。