ReactJS 组件丢失用户输入的输入值
ReactJS component loses input values entered by the user
我有一个像这样的 ReactJS 组件:
import React from 'react'
import {observer} from 'mobx-react'
@observer class InputForm extends React.Component{
render(){
if(this.props.store.tab1.isSelected){
return <form><input type="text"/></form>
}else if(this.props.store.tab2.isSelected){
return <form><input type="checkbox"/></form>
}
}
}
The way this component works: when tab1
is selected, the component returns a text box in which user can type a text.如果选择 tab2
,组件 returns 一个用户可以选中的复选框。
我的问题是,每当用户将选项卡从 tab1 切换到 tab2 时,反之亦然,用户输入的文本将丢失或复选框将失去其复选标记。
我想知道如何让文本框或复选框在用户来回切换选项卡时保留其用户输入的值。
因为 react 会在呈现复选框时删除输入 dom 和 vice-versa。您必须将值存储在状态中,并在呈现输入或复选框时使用它们。请注意,下面的代码是提示性的。它可能需要更多的调整。
@observer class InputForm extends React.Component{
super() {
this.state = {value : '', checked : false};
}
onChangeInput (e) { this.setState({value : e.target.value});}
onChangeCheckbox (e) {this.setState({checked : e.target.checked});}
render(){
if(this.props.store.tab1.isSelected){
return <form><input onChange=this.onChangeInput.bind(this) type="text" value={this.state.value}/></form>
}else if(this.props.store.tab2.isSelected){
return <form><input onChange=this.onChangeChecbox.bind(this) type="checkbox" checked={this.state.checked}/></form>
}
}
}
我有一个像这样的 ReactJS 组件:
import React from 'react'
import {observer} from 'mobx-react'
@observer class InputForm extends React.Component{
render(){
if(this.props.store.tab1.isSelected){
return <form><input type="text"/></form>
}else if(this.props.store.tab2.isSelected){
return <form><input type="checkbox"/></form>
}
}
}
The way this component works: when tab1
is selected, the component returns a text box in which user can type a text.如果选择 tab2
,组件 returns 一个用户可以选中的复选框。
我的问题是,每当用户将选项卡从 tab1 切换到 tab2 时,反之亦然,用户输入的文本将丢失或复选框将失去其复选标记。
我想知道如何让文本框或复选框在用户来回切换选项卡时保留其用户输入的值。
因为 react 会在呈现复选框时删除输入 dom 和 vice-versa。您必须将值存储在状态中,并在呈现输入或复选框时使用它们。请注意,下面的代码是提示性的。它可能需要更多的调整。
@observer class InputForm extends React.Component{
super() {
this.state = {value : '', checked : false};
}
onChangeInput (e) { this.setState({value : e.target.value});}
onChangeCheckbox (e) {this.setState({checked : e.target.checked});}
render(){
if(this.props.store.tab1.isSelected){
return <form><input onChange=this.onChangeInput.bind(this) type="text" value={this.state.value}/></form>
}else if(this.props.store.tab2.isSelected){
return <form><input onChange=this.onChangeChecbox.bind(this) type="checkbox" checked={this.state.checked}/></form>
}
}
}