react入门—08react表单

react

1.简介

2.实例 

受控组件的写法

import React from 'react'

class CommentBox extends React.Component{

constructor(props){

super(props)

this.state = {

value: ''

}

this.handleChange = this.handleChange.bind(this)

this.handleSubmit = this.handleSubmit.bind(this)

}

handleChange(event){

this.setState({

value: event.target.value

})

}

handleSubmit(event){

alert(this.state.value)

event.preventDefault()

}

render(){

return (

<form className="p-5" onSubmit={this.handleSubmit}>

<div className="form-group">

<label>留言内容</label>

<input

type="text"

className="form-control"

placeholder="请输入内容"

onChange={this.handleChange}

value={this.state.value}

/>

</div>

<button type="submit" className="btn btn-primary">

留言

</button>

</form>

)

}

}

export default CommentBox

非受控组件

import React from 'react'

class CommentBox1 extends React.Component{

constructor(props){

super(props)

this.handleSubmit = this.handleSubmit.bind(this)

}

handleSubmit(event){

alert(this.textInput.value + '1')

event.preventDefault()

}

render(){

return (

<form className="p-5" onSubmit={this.handleSubmit}>

<div className="form-group">

<label>留言内容</label>

<input

type="text"

className="form-control"

placeholder="请输入内容"

ref={(textInput)=>{this.textInput = textInput}}

/>

</div>

<button type="submit" className="btn btn-primary">

留言

</button>

</form>

)

}

}

export default CommentBox1

以上是 react入门—08react表单 的全部内容, 来源链接: utcz.com/z/382442.html

回到顶部