React - The First Try

首先react也会有个root 组建,他的特征就是需要提供一个元素都selector (这里的ID)


//this is the root component which including other comps
class CommentBox extends React.Component<any, any> {
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
</div>
)
}
}

ReactDOM.render(<CommentBox />, document.getElementById("targetreact"));

主index.html

<div id="targetreact"></div>

看下组建的定义

// Base component for plain JS classes
class Component<P, S> implements ComponentLifecycle<P, S> {
constructor(props?: P, context?: any);
setState(f: (prevState: S, props: P) => S, callback?: () => any): void;
setState(state: S, callback?: () => any): void;
forceUpdate(callBack?: () => any): void;
render(): JSX.Element;

// React.Props<T> is now deprecated, which means that the `children`
// property is not available on `P` by default, even though you can
// always pass children as variadic arguments to `createElement`.
// In the future, if we can define its call signature conditionally
// on the existence of `children` in `P`, then we should remove this.
props: P & { children?: ReactNode };
state: S;
context: {};
refs: {
[key: string]: ReactInstance
};
}

两个参数 ,props 和 stats
props相当于NG2 里的 inputs, stats还没接触,后续再说

  • NG2 => inputs

基础例子里只用了render, 其实就是组建自身的jsx结构,当然带了 props 和stats这种变量
props里的children 属相相当于 组建内部的东西

  • NG2 => ng-content

<Comment author="perter">this is one comment</Comment> 就是这里的this isxxx

用了ts,有些不同,如果参数props 和stats没有类型要给any,有的话要明确

如下


class Comment extends React.Component<{ author?: string }, any>{
rawMarkup() {
var rawMarkup = marked(this.props.children.toString(), { sanitize: true });
return { __html: rawMarkup };
};

render() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{/**not recommended way to render html */}
<span dangerouslySetInnerHTML={this.rawMarkup() } />
</div>
);
}
}

上面的例子看注释的写法…普通 //会被输出的.我哭…

这里用了一个dangerouslySetInnerHTML 来把string的html 渲染出来..不建议用.. eval的感觉你懂的

  • NG2 => [innerHTML]