JSX语法
这个有趣的标签语法既不是字符串也不是 HTML,它被称为 JSX
const element = <h1>Hello, world!</h1>;
- index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Man from './components/Man';
import God from './components/God';
import reportWebVitals from './reportWebVitals';
let hello = React.createElement("h1",{id:"box",className:"box1"},"Heelo world!")
let str1 = <div>this is str1</div>
let sum = function(a,b){
return a+b
}
ReactDOM.render(
<div>
{hello} {/* 普通的数据绑定 */}
<h3>{str1}</h3> {/* 绑定一个jsx语法的变量 */}
<h3>{sum(1,2)}</h3>{/* 函数表达式 */}
<h3>{4+5}</h3>{/* 计算表达式 */}
<h3>{10>9?'正确':'错误'}</h3>{/* 计算表达式 */}
<God name="上帝" task="世界和平"></God>
<Man name="普通人" task="好好工作,努力赚钱"></Man>
</div>
,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
class组件
- Man.js
import React from "react";
class Man extends React.Component{
render(){
return (
<div className="Man">
<h3>我是man组件</h3>
{/* 类组件,获取组件参数的时候,使用this.props.xxx */}
<div>我是{this.props.name},任务是{this.props.task}</div>
</div>
)
}
}
export default Man;
函数组件
- God.js
// 使用对象的解构赋值语法,获取useState钩子,用来给函数组件添加state
import React,{useState} from "react";
import Man from "./Man"
function God(props){
const [able,setAble] = useState("实现普通人的愿望!");
return(
<div className="Man">
<i>上帝的能力是{able}</i>
<h3>我是God组件</h3>
{/* 函数组件,在获取组件参数的时候,添加props参数 */}
<div>我是{props.name},任务是{props.task}</div>
<Man name="小学生" task="好好学习"></Man>
</div>
)
}
export default God