创建组件的方法
var 组件名(首字母大写) = React.createClass({
//该对象中还会有其他键值对,render 只是其中之一,作用是渲染界面,还可以设置声明周期,自定义属性等等...
render:function() {
return 组件结构;
}
* })
注意:如果组件名不大写,使用时会被认为时自定标签,不会出现组件该有的效果
var HelloWorld = React.createClass({
render:function() {
return <h1>HelloWorld</h1>;
}
})
组件的使用方式
双标签使用
ReactDOM.render(
<HelloWorld></HelloWorld>,
document.getElementById("box")
)
单标签使用 注意遵循 xhtml 后边加入斜杠 /
ReactDOM.render(
<HelloWorld />,
document.getElementById("box")
)
props:
每个组件自带 props 属性,该属性是只读的在组件使用时定义的属性都会在 props对象中以键值对的形式进行存储
var HelloWho = React.createClass({
render:function() {
return <h1>hello,{this.props.name}</h1>
;
}
})
ReactDOM.render(
<HelloWho name="逆势谁" />,
box
)
组件设置样式的几种方法
var cs = {
color:"red"
}
var CssSTyle = React.createClass({
render:function() {
return <div>
<h1 className = "one">外部样式</h1>//根据 class 值直接在css文件或 style标签中添加样式
<h1 style={{color:"blue"}}>行间样式1</h1>
<h1 style ={cs}>行间样式2</h1>
</div>
}
})
ReactDOM.render(
<CssSTyle />,
box
)
组件创建的另外几个方法
通过 函数创建
//传值 用 props 作为函数参数 props 会存储 name的值 键值对形式
function Welcome (props) {
return (
//根节点之外直接写
<div>
{/*这里这样写*/}
<h1>你好,卡路里</h1>
<h1>{props.name}</h1>
</div>)
}
ReactDOM.render(
<Welcome name="杨超越" />,
box
)
通过class创建
/*
* 通过class创建组件
*/
class Hello extends React.Component{
constructor(props){
super(props)
}
//class 方式创建组件时在 render 函数中写组件
render(){
return <div>
<h1>你好,北京欢迎你</h1>
<h1>{this.props.name}</h1>
</div>
}
}
ReactDOM.render(
<Hello name="杨超越" />,
box
)
组合
//合体
var Word = React.createClass({
render:function(){
return <div>
<Welcome name={this.props.one} />
<Hello name="杨超越" />
</div>
}
})
ReactDOM.render(
<Word one ="china" />,
box
)