Uncontrolled elements — such as text inputs, checkboxes, radio buttons, and entire forms with inputs — can always be uncontrolled or controlled.
import React from 'react';
const App = () => (
<div>
<label>
My uncontrolled Input: <input type="text" />
</label>
</div>
);
export default App;
上面这段代码,我们没有对input进行value和onChange变化的管理,input通过内部机制管理自己的状态
在线运行:https://stackblitz.com/edit/react-syr4se
import React, { useState } from 'react';
const App = () => {
const [value, setValue] = useState('');
// const [value, setValue] = useState("Uncontrolled component");
const handleChange = event => setValue(event.target.value);
return (
<div>
<label>
My still uncontrolled Input:
<input type="text" onChange={handleChange} />
</label>
<p>
<strong>Output:</strong> {value}
</p>
</div>
);
};
export default App;
以上是一个非受控组件,input区域是通过内部机制获取到的value,而output是通过state获取的value
- input field receives its value from internal DOM node state
- output paragraph receives its value from React’s state
非受控组件可能会带来意想不到的bug,很多时候我们希望通过一个数据来源控制UI,通常是相同的props,state渲染相同的输出_: (props, state) => view
.
我们可以通过给input设置value的属性,从而将非受控转化为受控组件,从而统一UI的数据来源
在线运行:https://stackblitz.com/edit/react-p4munb
import React from "react";
import "./style.css";
import React, { useState } from 'react';
const App = () => {
const [value, setValue] = useState('Hello React');
const handleChange = event => setValue(event.target.value);
return (
<div>
<label>
My controlled Input:
<input type="text" value={value} onChange={handleChange} />
</label>
<p>
<strong>Output:</strong> {value}
</p>
</div>
);
};
export default App;