npx create-react-app 项目名
1、参数赋值
function App() {
const divTitle = '标签内容'
const flag = true
let divContent = null
if (flag) {
divContent = <span>flag为true</span>
}else {
divContent = <p>flag为false</p>
}
return (
<div title={divTitle}>
{divContent}
</div>
);
}
export default App;
2、遍历数组
import { Fragment } from 'react';
import { Fragment } from 'react';
import './App.css';
function App() {
const list = [
{ id: 1, name: '小王' },
{ id: 2, name: '小吴' },
{ id: 3, name: '小张' }
]
const datas = list.map(item => {
return <Fragment>
<li key={item.id}>{item.name}</li>
<li>=====</li>
</Fragment>
})
return (
<ul>{datas}</ul>
);
}
export default App;
3、事件
import { useState } from 'react';
//字符串
function App() {
const [content, setConent] = useState('标签默认内容')
function handleClick() {
setConent('新内容')
}
return (
<>
<div>{content}</div>
<button onClick={handleClick}>按钮</button>
</>
);
}
//对象
function App() {
const [contents, setConent] = useState({
title: '默认标题',
content: '默认内容'
})
function handleClick() {
setConent(
{
...contents,
content: '新内容'
}
)
}
return (
<>
<div>{contents.content}</div>
<button onClick={handleClick}>按钮</button>
</>
);
}
//数组
function App() {
const [contents, setConent] = useState([
{ id: 1, name: '小王' },
{ id: 2, name: '小吴' },
{ id: 3, name: '小张' }
])
const listData = contents.map(item => {
return <li key={item.id}>{item.name}</li>
})
let id = 3;
function handleClick() {
setConent(
[
...contents,
{id: ++id, name: "小花"}
]
)
}
return (
<>
<ul>{listData}</ul>
<button onClick={handleClick}>按钮</button>
</>
);
}
export default App;