Skip to main content

组件编程-受控组件与非受控组件

组件分类

  • 受控组件: 先存后取state

    • 页面中所有输入类DOM, 随着输入存入状态, 需要时取状态
  • 非受控组件: 现用现取ref

    • 页面中所有输入类DOM, 都是现用现取内容

主要目的

减少使用 ref 属性, 避免效率问题

Login案例

受控组件

<script type="text/babel">

class Login extends React.Component{

state = {
username:'',
password:''
}

handleSubmit = (event) =>{
event.preventDefault()
const {username, password} = this.state;
alert(`输入的用户名为:${username} 输入的密码为:${password}`)
}

saveUsername = (event)=>{
this.setState({username:event.target.value})
}

savePassword = (event)=>{
this.setState({password:event.target.value})
}

render(){
return (
<form onSubmit={this.handleSubmit} >
用户名<input type="text" onChange={this.saveUsername} name="username)
密码<input type="password" onChange={this.savePassword} name="password)
<button>提交</button>
</form>
)
}
}

ReactDOM.render(<Login/>, document.getElementById("test"))

</script>

非受控组件

<script type="text/babel">

class Login extends React.Component{

handleSubmit = (event) =>{
event.preventDefault()
const {username, password} = this;
alert(`输入的用户名为 ${username.value}, 输入的密码为 ${password.value}`);
}

render(){
return (
<form onSubmit={this.handleSubmit} >
用户名<input type="text" ref={c => this.username = c} name="username)
密码<input type="password" ref={c => this.password = c} name="password)
<button>提交</button>
</form>
)
}
}

ReactDOM.render(<Login/>, document.getElementById("test"))

</script>