主题
表单
输入框
- 表单的值,受 state 控制
- 需要自行监听
onCange
,更新 state
jsx
class On extends Component {
onstructor(props){
super(props)
this.state = {
data: ''
}
this.changeData = this.changeData.bind(this)
}
changeData = (e) => {
this.setState({
data: e.target.value
})
}
render(){
return (
{/* 受控组件:input value的值受 this.state.data 控制 */}
<input value={this.state.data} onClick={this.changeData} />
)
}
}
select
jsx
// 数据为 string
this.state = {
data: ''
}
// 监听改变
changeData = (e) => {
this.setState({
data: e.target.value
})
}
<select value={this.state.data} onChange={this.changeData}>
<option value="a">A</option>
<option value="b">B</option>
</select>
checkbox
jsx
class Checkbox extends Component{
constructor(props) {
super(props)
this.state = {
checkboxList: [
{value: 'A', checked: false},
{value: 'B', checked: false},
{value: 'C', checked: false}
]
}
this.changeChecked = this.changeChecked.bind(this)
}
changeChecked(index) {
const checkboxList = [ ...this.state.checkboxList ] // 复制一份出来
checkboxList[index].checked = !checkboxList[index].checked
this.setState({
checkboxList
})
}
render() {
return (
this.state.checkboxList.map((item, index) => (
<input
type="checkbox"
key={item.value}
value={item.value}
checked={item.checked}
onChange={() => {this.changeChecked(index)}}
/>
))
)
}
}
radio
jsx
class Radio extends Component{
constructor(props) {
super(props)
this.state = {
answer: 'a'
}
this.changeChecked = this.changeChecked.bind(this)
}
changeChecked = (e) => {
this.setState({
answer: e.target.value
})
}
render() {
return (
<div>
A <input type="radio" name="answer" value="a" checked={this.state.answer === 'a'} onChange={this.changeChecked} />
B <input type="radio" name="answer" value="b" checked={this.state.answer === 'b'} onChange={this.changeChecked} />
C <input type="radio" name="answer" value="c" checked={this.state.answer === 'c'} onChange={this.changeChecked} />
</div>
)
}
}