1.非受控组件
就是数据实拿实用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="text"></div>
<!-- React核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- 用于支持React操作DOM -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 将jsx转换成js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<!-- 对标签属性进行限制 -->
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/babel">
class Dome extends React.Component{
//表单提交的回调
handleSubmit = (event)=> {
event.preventDefault()//组织表单提交
const {admin,pwd} = this
alert(`您的账号是:${admin.value},你的密码是${pwd.value}`)
}
render(){
return(
<form action="#" onSubmit={this.handleSubmit}>
用户名:<input ref={c => this.admin = c} type="text" name='admin' />
密 码:<input ref={c => this.pwd = c} type="password" name='pwd' />
<button type='submit'>提交</button>
</form>
)
}
}
//渲染组件
ReactDOM.render(<Dome/>,document.getElementById('text'))
</script>
</body>
</html>
1受控组件
把数据放到state中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="text"></div>
<!-- React核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- 用于支持React操作DOM -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 将jsx转换成js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<!-- 对标签属性进行限制 -->
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/babel">
class Dome extends React.Component{
//初始化状态
state = {admin:'',pwd:''}
saveFormDate = (dataType)=>{
return (event)=>{
this.setState({[dataType] : event.target.value})
}
}
//表单提交的回调
handleSubmit = (event)=>{
event.preventDefault()//组织表单提交
const {admin,pwd} = this.state
alert(`你的账号是:${admin},你的密码是${pwd}`)
}
render(){
return(
<form action="#" onSubmit={this.handleSubmit}>
用户名:<input onChange={this.saveFormDate('admin')} type="text" name='admin' />
密 码:<input onChange={this.saveFormDate('pwd')} type="password" name='pwd' />
<button type='submit'>提交</button>
</form>
)
}
}
//渲染组件
ReactDOM.render(<Dome/>,document.getElementById('text'))
</script>
</body>
</html>