6. 表单数据绑定

This commit is contained in:
shikong 2024-10-25 19:59:53 +08:00
parent c32ebc5ad1
commit 1cbf245a2f
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
2 changed files with 51 additions and 0 deletions

View File

@ -2,6 +2,7 @@ import React from "react";
// import logo from './logo.svg';
import './App.css';
import InputComponent from "./components/InputComponent";
function App() {
// vue3 组合式 API
// React 必须大写 Pascal 命名 组件
@ -195,6 +196,8 @@ function App() {
</div>
<IfComponent/>
<InputComponent/>
</header>
</div>
);

View File

@ -0,0 +1,48 @@
import {useEffect, useState} from "react";
export default function InputComponent() {
const [state, setState] = useState({
inputValue: "666",
checkedArr: []
})
function onChecked(e) {
let tmp = [...state.checkedArr]
if (e.target.checked) {
tmp.push(e.target.value)
} else {
let index = tmp.indexOf(e.target.value)
tmp.splice(index, 1)
// checkedArr: [...state.checkedArr].slice(0, index).concat([...state.checkedArr].slice(index + 1))
}
setState({
...state,
checkedArr: tmp
})
}
useEffect(() => {
console.log(state.checkedArr)
}, [state.checkedArr]);
return <div style={{border: "1px solid", width: "80%"}}>
<div>
{state.inputValue}
</div>
<input onInput={(e) => {
setState({
...state,
inputValue: e.target.value
})
}}
value={state.inputValue}/>
<div>
<input value={1} onChange={onChecked} type="checkbox" name="options"/> 选项1
<input value={2} onChange={onChecked} type="checkbox" name="options"/> 选项2
<input value={3} onChange={onChecked} type="checkbox" name="options"/> 选项3
</div>
</div>
}