I was learning React and wanted to learn how to properly use forms. Then I found out that there is something called Controlled forms so I wrote this code:
<input
name='name'
value={this.state.name}
onChange={e => this.handleChange(e)}
/>
Is it optional to use "value" attribute since we already add the input data to state with onChange
? Is it true that value is needed just to ensure that the input data is properly added to the state? Just to be confident?
A controlled component can be set by state or props because you give it a value property. If you do not provide an onChange to a controlled component then you cannot change it's value because the value
property comes from state or props.
An uncontrolled component does not have a value
property so it manages it's own value, when the user types something in a textbox then it'll show that text. You can add onChange to an uncontrolled component but you can't reset it (because it doesn't have a value property).
const App = () => { const [controlled, setControlled] = React.useState(''); const onChange = React.useCallback( e => setControlled(e.target.value), [] ); return ( <div> <div> <label> contolled (can also set value with uncontrolled) <input type="text" value={controlled} onChange={onChange} /> </label> </div> <div> <label> contolled but no onChange, just follows other inputs <input type="text" value={controlled} /> </label> </div> <div> <label> uncontrolled (can never set it's value) <input type="text" onChange={onChange} /> </label> </div> </div> ); }; ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.