react組件渲染和父子組件之間的通信
1. 創(chuàng)建應(yīng)用
npx create-react-app react-demo
cd react-demo
npm run start/yarn start
可能會(huì)遇到如下報(bào)錯(cuò):
error @typescript-eslint/eslint-plugin@2.25.0: The engine "node" is incompatible with this module. Expected version "^8.10.0 || ^10.13.0 || >=11.10.1". Got "9.6.1"
error Found incompatible module.
執(zhí)行以下命令之后,重新創(chuàng)建
yarn config set ignore-engines true
2. jsx 語(yǔ)法
1、返回標(biāo)簽形式的代碼結(jié)構(gòu)
2、標(biāo)簽里可以寫表達(dá)式,但不可以是語(yǔ)句
3、特定屬性
i 通過(guò)使用引號(hào),來(lái)將屬性值指定為字符串字面量
ii 也可以使用大括號(hào),來(lái)在屬性值中插入一個(gè) JavaScript 表達(dá)式。
4、JSX 表示對(duì)象:createElement
jsx
const element = (
<h1 className="greeting">
Hello, world!
</h1>
)
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
// 注意:這是簡(jiǎn)化過(guò)的結(jié)構(gòu)
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
3. 元素渲染
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));
4. 組件props
- 自定義組件
- 自定義組件接收的屬性,轉(zhuǎn)換為單個(gè)對(duì)象props來(lái)獲取
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
5. 編輯todoList demo演示state操作,父子組件傳參
- todoList通過(guò)按鈕實(shí)現(xiàn)增加刪除和綁定
- 組件拆分,將todoList拆分成todoItem:父組件通過(guò)屬性傳 遞參數(shù)給子組件,子組件通過(guò)props來(lái)接收
- 子組件向父組件傳值:要調(diào)用父組件傳遞的方法
- 代碼優(yōu)化
6. css樣式
className\style\fragment