React Components
used to create encapsulations with embedded state
var myClass=React.creatClass({
render:function(){
...
}
});
调用后返回一个至少包含render方法的对象。这个对象就被称之为component(组件);
当createElement时,当做参数传入,则react自动调用该对象创建element。
var element=React.createElement(myComponent);
or using JSX :
<myComponent />; //这倒霉东西原来是这么用的
render:
var component = ReactDOM.render(element, document.getElementById('example'));
(可实现级联调用,因为返回值也是一个component对象)
返回的component的状态会被保存,就算再调用一次ReactDOM.render(element, document.getElementById('example')); 得到的对象跟之前的对象是相同的:
var componentA = ReactDOM.render(<MyComponent />, document.getElementById('example'));
var componentB = ReactDOM.render(<MyComponent />, document.getElementById('example'));
componentA === componentB; // true
This is why you shouldn't construct your own instance. Instead, ReactElement is a virtual ReactComponent before it gets constructed. An old and new ReactElement can be compared to see if a new ReactComponent instance is created or if the existing one is reused.
The render method of a ReactComponent is expected to return another ReactElement. This allows these components to be composed. Ultimately the render resolves into ReactElement with a string tag which instantiates a DOM Element instance and inserts it into the document.
参数接口
入口点(Entry Point)
React.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent;
节点和元素(Nodes and Elements)
type ReactNode = ReactElement | ReactFragment | ReactText; type ReactElement = ReactComponentElement | ReactDOMElement; type ReactDOMElement = { type : string, props : { children : ReactNodeList, className : string, etc. }, key : string | boolean | number | null, ref : string | null }; type ReactComponentElement<TProps> = { type : ReactClass<TProps>, props : TProps, key : string | boolean | number | null, ref : string | null }; type ReactFragment = Array<ReactNode | ReactEmpty>; type ReactNodeList = ReactNode | ReactEmpty; type ReactText = string | number; type ReactEmpty = null | undefined | boolean;
类和组件(Classes and Components)
type ReactClass<TProps> = (TProps) => ReactComponent<TProps>; type ReactComponent<TProps> = { props : TProps, render : () => ReactElement };
组件中props
就这么用:
var Photo = React.createClass({
render: function() {
return (
<div className='photo'>
<img src={this.props.imageURL} />
<span>{this.props.caption}</span>
</div>
)
}
});
React.render(<Photo imageURL='http://tinyurl.com/lkevsb9' caption='New York!' />, document.body);