2. 事件绑定

This commit is contained in:
shikong 2024-10-23 19:33:04 +08:00
parent b8a4c8f37e
commit 591b3eaafa
Signed by: Shikong
GPG Key ID: BD85FF18B373C341

View File

@ -3,71 +3,97 @@ import React from "react";
import './App.css';
function App() {
// vue3 组合式 API
// React 必须大写 Pascal 命名 组件
function FnHello({name="Fn"}){
return <div>Hello world By {name}</div>
}
let com = FnHello({name:"obj"})
function FnHello2(){
return React.createElement("div", [], "Hello world By React.createElement")
}
// vue2 选项式 API
class ClassHello extends React.Component {
// eslint-disable-next-line no-useless-constructor
constructor(props) {
super(props);
// vue3 组合式 API
// React 必须大写 Pascal 命名 组件
function FnHello({name = "Fn"}) {
return <div>Hello world By {name}</div>
}
render() {
return <div>Hello world By Class</div>
let com = FnHello({name: "obj"})
function FnHello2() {
return React.createElement("div", [], "Hello world By React.createElement")
}
}
// React 不能直接渲染 js 对象
let obj = {
a: 1,
b: 2
}
// vue2 选项式 API
class ClassHello extends React.Component {
// eslint-disable-next-line no-useless-constructor
constructor(props) {
super(props);
}
// 如果是数组则依次遍历
let arr1 = [
1,
2,
3
]
render() {
return <div>Hello world By Class</div>
}
}
let arr2 = [
FnHello({name:"arr1"}),
FnHello({name:"arr2"}),
FnHello({name:"arr3"}),
]
// React 不能直接渲染 js 对象
let obj = {
a: 1,
b: 2
}
return (
<div className="App">
<header className="App-header">
{/*<img src={logo} className="App-logo" alt="logo" />*/}
<FnHello/>
// 如果是数组则依次遍历
let arr1 = [
1,
2,
3
]
<FnHello2/>
let arr2 = [
FnHello({name: "item1"}),
FnHello({name: "item2"}),
FnHello({name: "item3"}),
]
<ClassHello/>
function clickHandler2() {
console.log("按钮2被点击")
}
{com}
function clickHandler3(arg, e) {
console.log("按钮3被点击, 参数 " + arg)
console.log("合成的事件对象", e)
// 阻止事件冒泡
e.stopPropagation()
}
{JSON.stringify(obj)}
return (
<div className="App">
<header className="App-header">
{/*<img src={logo} className="App-logo" alt="logo" />*/}
<FnHello/>
<br/>
<FnHello2/>
{arr1}
<ClassHello/>
{arr2}
</header>
</div>
);
{com}
{JSON.stringify(obj)}
<br/>
{arr1}
{arr2}
<div style={{display: 'flex'}}>
{/*事件绑定*/}
<button onClick={() => {
console.log("按钮1被点击")
}}>按钮1
</button>
<button onClick={clickHandler2}>按钮2</button>
</div>
<div>
<button onClick={clickHandler3.bind(this, "按钮3")}>按钮3</button>
<button onClick={(e) => clickHandler3("按钮3", e)}>按钮3</button>
</div>
</header>
</div>
);
}
export default App;