React 学习(八) 受控组件和非受控组件
Controlled & Uncontrolled Components
Data is handle by a React Component ? Controlled : Uncontrolled
-
Controlled Components: The values in the components are always consistent with the state
import React, { PureComponent } from "react"; class App extends PureComponent { constructor() { super(); this.state = { message: "DefaultText", counter: 5, }; } changeHandle(e) { // console.log(e.target.value); this.setState({ message: e.target.value, }); } submitHandle(e) { e.preventDefault(); console.log(this.state.message); } render() { const { message } = this.state; return ( <> <div>message:{message}</div> <form onSubmit={(e) => { this.submitHandle(e); }} > <label htmlFor="message"> <input type="text" onChange={(e) => { this.changeHandle(e); }} value={message} /> </label> <input type="submit" /> </form> </> ); } } export default App;
sequenceDiagram participant s as state participant c as components s->>c:DefaultValue loop One Way Data Flaw c->>c:ChangeValue c->>s:ChangeState s->>c:ChangeValue end -
Uncontrolled Components
import React, { createRef, PureComponent } from "react"; export default class App extends PureComponent { constructor(props) { super(); this.state = { username: "", }; this.usernameRef = createRef(); } render() { return ( <div> <form onSubmit={(e) => { this.handleSubmit(e); }} > <label htmlFor="username"> Username:{" "} <input type="text" name="username" id="username" ref={this.usernameRef} /> </label> <input type="submit" value="submit" /> </form> </div> ); } handleSubmit(event) { event.preventDefault(); console.log(this.usernameRef.current.value); } }
每天进步一点点