reactjs - 無法在 react 輸入欄位中輸入
我有一個簡單的表單,上面有一個無法輸入的輸入欄位。我一開始以為問題出在 onChange 或 value 屬性,這些屬性會將輸入設為唯讀,但事實是即使用瀏覽器的建議輸入也可以,而且狀態更新得很好(參見這裡的 GIF),只是鍵盤無法讓我輸入,即使重新載入頁面後也是如此。
我也有一個登入頁面,除了當我登出並重定向回該頁面時,它不會正常工作,直到我重新加載頁面,現在它就能正常工作了。
<input
value={name}
onChange={handleChange}
name="name"
/>
const [name, setName] = useState("");
const handleChange = (e:any) => {
setName(e.target.value);
}
奇怪的是它好像處於唯讀狀態,但當我使用瀏覽器的建議時,它卻能正常工作並更新狀態。
這是整個組件:
import React, { useEffect, useState } from 'react';
import { useForm } from '../../utils/useForm';
import { CubeType } from '../../interfaces';
//import useStore from '../store/Store';
import { Modal, Button, Row, Col, FormGroup, FormLabel, FormControl } from 'react-bootstrap';
type Props = {
show: Boolean,
onClose: () => void,
cubeTypes: CubeType[]
};
const ModalTimelist = (props: Props) => {
//const store = useStore();
const [values, handleChangee] = useForm({ cubeType: 1, name: '' });
const [name, setName] = useState("");
const handleChange = (e:any) => {
setName(e.target.value);
}
useEffect(() => {
const modal = document.getElementsByClassName('modal')[0];
if(modal) modal.removeAttribute('tabindex');
}, [props.show]);
return (
<>
<Modal show={props.show} onHide={ props.onClose }>
<Modal.Header>
<Modal.Title>Timelist { name }</Modal.Title>
</Modal.Header>
<Modal.Body>
<Row>
<Col md="3">
<FormGroup>
<FormLabel>Cube Type</FormLabel>
<select
value={values.cubeType}
onChange={ handleChangee }
className="form-select"
name="cubeType"
>
{props.cubeTypes.map((it, idx) => {
return (<option value={ idx } key={"cube"+idx}>{it.name}</option>);
}) }
</select>
</FormGroup>
</Col>
<Col md="9">
<FormGroup>
<FormLabel>Name</FormLabel>
<FormControl
value={name}
onChange={handleChange}
name="name"
/>
</FormGroup>
</Col>
</Row>
</Modal.Body>
<Modal.Footer>
<Button variant="success" onClick={() => props.onClose()}>
Save
</Button>
<Button variant="outline-danger" onClick={() => props.onClose()}>
Cancel
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default ModalTimelist;
答案#1
輸入的值必須是狀態值,否則它不會改變,使用這段代碼
const App = () => {
const [name,setName] = useState("")
const handle = ({target:{value}}) => setName(value)
return <input
value={name}
onChange={handle}
name="name"
/>
}
答案#2
在狀態上設置名稱時使用防彈跳(debounce)。
範例:
const handleChange = (e:any) => {
debounce(() => { setName(e.target.value) }, 300);
}
