jsx表达式,样式,函数式组件,类组件
注意:
1.jsx必须要有根节点
2.正常的普通的HTML元素要小写。如果大写默认为组件。
表达式
1.由HTML元素构成
2.如果中间需要插入变量用{}
3.{}中间可以使用表达式
4.{}中间表达式可以使用jsx对象
5.属性和HTML类容一样都是用{}来插入类容
let man = '发热'; let element2 = ( <div> <h1>今天是否隔离</h1> <h2>{man=="发热"?<button>隔离</button>:"躺床上"}</h2> </div> ) //let man = '发热'; let element4 = ( <div> <span>横着躺</span> <span>竖着躺</span> </div> ) man = '正常' let element3 = ( <div> <h1>今天是否隔离</h1> <h2>{man=="发热"?<button>隔离</button>:element4}</h2> </div> ) let color = 'bgRed' let logo = 'https://www.baidu.com/img/pc_1c6e30772d5e4103103bd460913332f9.png' //HTML的样式类名要写className,因为class在js当中是关键词 let element5 = ( <div className={color}> <img src={logo} /> 红色的背景颜色 </div> ) ReactDOM.render( element5, document.getElementById('root') )
JSX_style 样式
1、Class,style中,不可以存在多个class属性
<div class=’abc’ class={‘active’}> 错误的表示
2、style样式中,如果存在多个单词的属性组合,第二个单词开始,首字母大写。或者用引号引起来,否则会报错。
let exampleStyle = { background:"skyblue", borderBottom:"4px solid red", 'background-image':"url(https://www.baidu.com/img/pc_1c6e30772d5e4103103bd460913332f9.png)" }
3、多个类共存的操作
let element2 = ( <div> <h1 className={"abc "+classStr}>helloworld</h1> </div> ) let classStr2 = ['abc2','redBg2'].join(" ") let element3 = ( <div> {/* 这里写注释 */} <h1 className={classStr2} style={exampleStyle}>helloworld</h1> </div> )
4、注释
必须在括号的表达式内书写,否则报错:
{/* 这里写注释 */}
React组件
函数式组件与类组件的区别和使用,函数式比较简单,一般用于静态没有交互事件内容的组件页面。类组件,一般又称为动态组件,那么一般会有交互或者数据修改的操作,比如点击事件。
1、函数式组件
//函数式组件 function Childcom(props){ console.log(props) let title = <h2>我是副标题</h2> let weather = props.weather //条件判断 let isGo = weather=='下雨' ?"不出门":"出门" return ( <div> <h1>函数式组件helloworld</h1> {title} <div> 是否出门? <span>{isGo}</span> </div> </div> ) }
2、类组件
//类组件定义 class HelloWorld extends React.Component{ render(){ console.log(this) return ( <div> <h1>类组件定义HELLOWORLD</h1> <h1>hello:{this.props.name}</h1> <Childcom weather={this.props.weather} /> </div> ) } }
3、复合组件:组件中又有其他的组件,复合组件中既可以有类组件又可以有函数组件
import React from 'react'; import ReactDOM from 'react-dom'; import './04style.css'; //函数式组件 function Childcom(props){ console.log(props) let title = <h2>我是副标题</h2> let weather = props.weather //条件判断 let isGo = weather=='下雨' ?"不出门":"出门" return ( <div> <h1>函数式组件helloworld</h1> {title} <div> 是否出门? <span>{isGo}</span> </div> </div> ) } //类组件定义 class HelloWorld extends React.Component{ render(){ console.log(this) //返回的都是JSX对象 return ( <div> <h1>类组件定义HELLOWORLD</h1> <h1>hello:{this.props.name}</h1> <Childcom weather={this.props.weather} /> </div> ) } }
ReactDOM.render(
<HelloWorld name="老陈" weather="下雨" />,
document.querySelector('#root')
)
来自于b站:https://space.bilibili.com/40018594?spm_id_from=333.788.b_765f7570696e666f.2