编写组件
页面结构
组件
注意:
- 组件必须继承React.Component
- 组件必须有constructor()且super父级,否则状态等功能无法使用
- 组件必须有render()方法
- 组件名(类名)必须首字母大写
- 组件使用时,单双标签都可以
- 组件中的HTML必须规范(双标签闭合,单标签结尾加/)
模板输出
输出变量,属性,方法...任何东西都可以
class Cmp1 extends React.Component{
constructor(...args){
super(...args);
this.age=18
}
fn(){
return 55
}
render (){
let name='张三';
return <div>
//输出变量
姓名:{name}<br/>
//输出属性
年龄:{this.age}<br/>
{this.fn()}
</div>
}}复制代码
输出到属性
class Cmp1 extends React.Component{
contructor(...args){
super(...args);
}
render(){
let a=12;
return <div>
<!-- 输出字符串”a“ -->
<div title="a">box1</div>
<!-- 输出变量 -->
<div title={a}>box2</div>
</div>;
}
}
复制代码
组件传参
用props
接受参数
class Cmp1 extends.Component{
constructor(...args){
super(..args)
}
render(){
return{
<div>
{this.props.a},{typeof(this.props.a)}
</div>
};
}
}
//方法1.字符串
//<Com1 a="12"/>
//12,string
//方法2.其他类型(数组,数字,json等)
//<Cmp1 a={12}/}
//12,number
//<Cmp1 a={{name:'blue'}}/>
//{name:blue,object}
复制代码
注意:如果希望给组件传递参数(数字,json等),必须使用{},否则传递的都是字符串
html组件的style
render(){
return{
//错误
<div style="width:200px;height:200px"></div>
//正确
<div style={{width:'200px',height:'200px'}}></div>
}
}
复制代码
注意:react中不存在{{}}写法,外面一层{}是react的表达式,里面一层{}是json的一部分
html组件的class
render(){
return{
<div className=“box1”>
组件类名
</div>
}
}复制代码