一、表單元素
????????像<input>、<textarea>、<option>這樣的表單元素不同于其他元素,因為他們可以通過用戶交互發生變化。這些元素提供的界面使響應用戶交互的表單數據處理更加容易
????????交互屬性,用戶對一下元素交互時通過onChange回調函數來監聽組件變化。表單元素支持幾個受用戶交互影響的屬性:
? ? ? ? value用于<input>、<textarea>
? ? ? ? checked用于<checkbox>、<radio>
? ? ? ? selected用于<option>
二、受限組件和不受限組件
1.受限組件與雙向數據綁定
受限組件:設置了value的<input>是一個受限組件,對于受限的<input>,渲染出來HTML元素始終保持value屬性的值,此時用戶在渲染出來的組件里輸入任何值都不起作用
?寫一個完整的表單元素的實例
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>受限組件和雙向綁定</title><script src="../js/react.development.js "></script><script src="../js/react-dom.development.js"></script><!-- 用于解析babel --><script src="../js/babel.min.js"></script>
</head><body><div id="hello"></div><div id="hello2"></div><script type="text/babel">//受限組件,他的class Hello extends React.Component{render(){return <div><input type="text" value='123'/><hr/></div>}}ReactDOM.render(<Hello />,document.getElementById('hello'))//雙向數據綁定class Hello2 extends React.Component{state = {value:'12345'}//valueChange = (e)=>{this.setState({value:e.target.value})}render(){return <div><input type="text" value={this.state.value} onChange={this.valueChange}/><p>{this.state.value}</p></div>}}ReactDOM.render(<Hello2 />,document.getElementById('hello2'))</script><!-- radio、checkbox、textarea、select --><hr/><div id="root1"></div><script type="text/babel">//表單元素的雙向綁定class Rtx extends React.Component{state = {//單選按鈕radioValue:'',//check選中的checkArr:[],//文本域的valuetextareaValue:'',selectArr: ['北京','上海','湖北','廣東'],//select選中的地址address:''}//radioChange = (e)=>{this.setState({radioValue:e.target.value})}checkboxChange =(e)=>{//由于組件繼承的是purecomponent,因此要將數組復制一次let _checkArr = [...this.state.checkArr]if (e.target.checked) {//將所有選中的復選框的value值,push到一個數組(checkArr)中_checkArr.push(e.target.value)} else {//若取消選中,則將其從checkArr中減掉_checkArr.splice(this.state.checkArr.indexOf(e.target.value), 1)}//利用setState更新checkArrthis.setState({checkArr:_checkArr})}textareaChange=(e)=>{this.setState({textareaValue:e.target.value})}selectChange=(e)=>{this.setState({address:e.target.value})}submit =()=>{console.log(this.state);}render(){let checkInfo=["c1",'c2']let {radioValue,checkArr,textareaValue,selectArr,address } =this.statelet {checkboxChange} =thisreturn <div><div>性別:男<input type="radio" value='man' checked={radioValue=='man'?true:false} onChange={this.radioChange}/>女<input type="radio" value='woman' checked={radioValue=='woman'?true:false} onChange={this.radioChange}/></div><div>{checkInfo.map(function(item,index){return <span>{item}<input type="checkbox" name='box' value={item} key={index} onChange={checkboxChange} checked={checkArr.indexOf(item)!==-1}></input></span> })}</div><div><textarea name="" id="" value={textareaValue} cols="30" rows="10" onChange={this.textareaChange}></textarea></div><div>地址:<select value={address} name="address" onChange={this.selectChange}>{selectArr.map(function(item,index){return <option key={index}>{item}</option>})}</select> </div><button disabled={!radioValue || !address || !checkArr || !textareaValue } onClick={()=>this.submit()}>提交</button></div>}}ReactDOM.render(<Rtx />,document.getElementById('root1'))</script><!-- radio、
</body></html>
2.不受限組件
不受限組件:?沒有設置value(或者設為null)的input組件是一個不受限組件。杜宇不受限的input組件,渲染出來的元素直接反映用戶輸入
?使用defaultValue屬性不使用value可以實現不受限組件的雙向數據
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>非受限組件</title><script src="../js/react.development.js "></script><script src="../js/react-dom.development.js"></script><!-- 用于解析babel --><script src="../js/babel.min.js"></script>
</head><body><div id="root1"></div><script type="text/babel">//非受限組件class Rtx extends React.Component {state = {value: '123'}valueChange = (e) => {this.setState({ value: e.target.value })console.log(this.state.value);}render() {return <div><div><input type="text" /><input type="text" defaultValue={this.state.value} onChange={this.valueChange} /><p>{this.state.value}</p></div><div>性別:男<input type="radio" name='sex' value='man' />女<input type="radio" name='sex' value='woman' /></div></div>}}ReactDOM.render(<Rtx />, document.getElementById('root1'))</script><!-- radio、checkbox、textarea、select --><div id="root1"></div><script type="text/babel">//表單元素的雙向綁定class Rtx extends React.Component {state = {//單選按鈕radioValue: '',//check選中的checkArr: [],//文本域的valuetextareaValue: '',selectArr: ['北京', '上海', '湖北', '廣東'],//select選中的地址address: ''}//radioChange = (e) => {this.setState({ radioValue: e.target.value })}checkboxChange = (e) => {//由于組件繼承的是purecomponent,因此要將數組復制一次let _checkArr = [...this.state.checkArr]if (e.target.checked) {//將所有選中的復選框的value值,push到一個數組(checkArr)中_checkArr.push(e.target.value)} else {//若取消選中,則將其從checkArr中減掉_checkArr.splice(this.state.checkArr.indexOf(e.target.value), 1)}//利用setState更新checkArrthis.setState({checkArr: _checkArr})}textareaChange = (e) => {this.setState({ textareaValue: e.target.value })}selectChange = (e) => {this.setState({ address: e.target.value })}submit = () => {console.log(this.state);}render() {let checkInfo = ["c1", 'c2']let { radioValue, checkArr, textareaValue, selectArr, address } = this.statelet { checkboxChange } = thisreturn <div><div>性別:男<input type="radio" defaultValue='man' checked={radioValue == 'man' ? true : false} onChange={this.radioChange} />女<input type="radio" defaultValue='woman' checked={radioValue == 'woman' ? true : false} onChange={this.radioChange} /></div><div>{checkInfo.map(function (item, index) {return <span>{item}<input type="checkbox" name='box' defaultValue={item} key={index}onChange={checkboxChange}checked={checkArr.indexOf(item) !== -1}></input></span>})}</div><div><textarea name="" id="" value={textareaValue} cols="30" rows="10" onChange={this.textareaChange}></textarea></div><div>地址:<select defaultValue={address} name="address" onChange={this.selectChange}>{selectArr.map(function (item, index) {return <option key={index}>{item}</option>})}</select></div><button disabled={!radioValue || !address || !checkArr || !textareaValue} onClick={() => this.submit()}>提交</button></div>}}ReactDOM.render(<Rtx />, document.getElementById('root1'))</script>
</body></html>
三、常用表單數據綁定
對相同邏輯的表單change事件進行封裝
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>表單提交</title><script src="../js/react.development.js "></script><script src="../js/react-dom.development.js"></script><!-- 用于解析babel --><script src="../js/babel.min.js"></script>
</head><body><div id="root1"></div><script type="text/babel">//非受限組件class Rtx extends React.Component {state = {name: 'fxt',sex:'1',address:'上海',textareaValue:'hello world'}//我們發現下面獲得改變值的方法都是一樣的,所以對一樣的邏輯函數進行封裝handleChange=(e)=>{console.log(e.target.name);let key = e.target.namethis.setState({[key]:e.target.value})// this.setState({[e.target.name]:e.target.value})}// getName=(e)=>{// this.setState({name:e.target.value})// }// getSex=(e)=>{// this.setState({sex:e.target.value})// }getAddress=(e)=>{this.setState({address:e.target.value})}getTextareaValue=(e)=>{this.setState({textareaValue:e.target.value})}submit = (e) => {// e.preventDefault();alert(JSON.stringify(this.state))}render() {let selectArr=['北京', '上海', '湖北', '廣東']let {name,sex,address,textareaValue}=this.statereturn <div><form action=""><label for="">姓名:<input type="text" name='name' defaultValue={name} onChange={this.handleChange}/></label> <label for=""><div>性別:<input type="radio" name="sex" value='1' defaultChecked={sex==1? true:false} id="" onChange={this.handleChange}/>男<input type="radio" name="sex" value='2' defaultChecked={sex==2? true:false} id="" onChange={this.handleChange}/>女</div></label> <label for=""><div>地址:<select defaultValue={address} name="address" onChange={this.getAddress}>{selectArr.map( (item, index) =>{return <option key={index}>{item}</option>})}</select></div></label><label for=""><div>備注:<textarea name="" id="" defaultValue={textareaValue} cols="30" rows="10" onChange={this.getTextareaValue}></textarea> </div></label><button disabled={!name || !address || !textareaValue || !sex} onClick={()=>{this.submit()} }>提交</button></form></div>}}ReactDOM.render(<Rtx />, document.getElementById('root1'))</script>
</body></html>
四、注冊功能實現
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>注冊表單驗證</title><script src="../js/react.development.js "></script><script src="../js/react-dom.development.js"></script><!-- 用于解析babel --><script src="../js/babel.min.js"></script><style>.error{color: red;}</style>
</head><body><div id="root1"></div><script type="text/babel">//非受限組件class Rtx extends React.Component {state = {name: '',nameError:"",passworld:'',passworldError:'',sex:'1',phone:'',phoneError:'',city:'北京',textareaValue:'hello world'}//單獨寫校驗規則的nameChange=(e)=>{let rule= /^[\w-]{4,10}$/ let value=e.target.valuelet error=''if(!value){error='請輸入昵稱'}else if(!rule.test(value)){error='請輸入4-10位的昵稱'}else{error=''}this.setState({name:value,nameError:error})}//進行校驗的表單元素統一封裝handleTest=(e)=>{let ruleArr={passworld:{rule:new RegExp(/^\S*(?=\S{6,12})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/),text:'密碼',error:'6-12位,至少包括一個大小寫字母、數字、特殊字符'},phone:{rule:new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/),text:'手機號',error:'請輸入正確的手機號'}}let value=e.target.valuelet key = e.target.namelet ruleInfo={}let error=''Object.keys(ruleArr).map((el)=>{if(el==key){ruleInfo=ruleArr[key]}})if(!value){error='請輸入'+ruleInfo.text}else if(!ruleInfo.rule.test(value)){error=ruleInfo.error}else{error=''}this.setState({[key]:value,[key+'Error']:error})}//不進行校驗的表單通過自定義屬性實現獲得要設置的值的key鍵handleChange=(e)=>{console.log(e.target.name);let key = e.target.namethis.setState({[key]:e.target.value})// this.setState({[e.target.name]:e.target.value})}//提交想提交值submit = (e) => {e.preventDefault()//阻止默事件let {name,passworld,sex,phone,city,textareaValue} =this.statelet data={name,passworld,sex,phone,city,textareaValue}alert(JSON.stringify(data))}render() {let selectArr=[{id:1,text:'北京'},{id:2,text: '上海'}, {id:3,text:'湖北'}]let {name,nameError,passworld,passworldError,sex,phone,phoneError,city,textareaValue}=this.statereturn <div><form action=""><label for="">昵稱:<input type="text" name='name' defaultValue={name} onChange={this.nameChange}/><span className='error'> * {nameError}</span></label> <label for=""><div>密碼:<input type="text" name='passworld' defaultValue={passworld} onChange={this.handleTest}/><span className='error'> * {passworldError}</span></div></label> <label for=""><div>性別:<input type="radio" name="sex" value='1' defaultChecked={sex==1? true:false} id="" onChange={this.handleChange}/>男<input type="radio" name="sex" value='2' defaultChecked={sex==2? true:false} id="" onChange={this.handleChange}/>女</div></label> <label for="">手機號:<input type="text" name='phone' defaultValue={phone} onChange={this.handleTest}/><span className='error'> * {phoneError}</span> </label> <label for=""><div>城市:<select defaultValue={city} name="city" onChange={this.handleChange}>{selectArr.map( (item, index) =>{return <option value={item.id} key={index}>{item.text}</option>})}</select></div></label><label for=""><div>備注:<textarea name="textareaValue" id="" defaultValue={textareaValue} cols="30" rows="10" onChange={this.handleChange}></textarea> </div></label><button disabled={!name || nameError|| !passworld || passworldError|| !sex || !phone ||phoneError || !city ||!textareaValue } onClick={this.submit }>提交</button></form></div>}}ReactDOM.render(<Rtx />, document.getElementById('root1'))</script>
</body></html>