React 受控组件和非受控组件表单提交
- 受控组件:受我们控制的组件
- 非控组件:不受我们控制的组件
受控组件
const NoteSection:React.FC= ()=>{
const [note, setNote] = useState('')
console.log(note);
return(
<Wrapper>
<label>
<span>备注:</span>
<input type="text" placeholder="点击写备注..."
value={note}
onChange={(e)=> setNote(e.target.value)}
/>
</label>
</Wrapper>
)
}
会随着每传入一个字母都会更新
非受控组件
const NoteSection: React.FC<Props> = (props) => {
const note = props.value;
const refInput = useRef<HTMLInputElement>(null);
const onBlur = () => {
if (refInput.current !== null) {
props.onChange(refInput.current.value);
}
};
return (
<Wrapper>
<label>
<span>备注:</span>
<input type="text" placeholder="点击写备注..."
ref={refInput}
defaultValue={note}
onBlur={onBlur}
/>
</label>
</Wrapper>
)
}
鼠标移出时才获得note