如何使用单个处理程序处理多个 TextInput?
How to multiple TextInput handle with single handler?
我已经为 TextInput 创建了通用 class 并多次使用它,但它的事件句柄使用相同的方法。我想在 textInput 中填充数据后处理数组数据。
此处添加了多个 textField 和单个 handleAddMore
。如何识别哪个 textInput 调用了 handleAddMore
.
根据数组数据动态添加的textField组件。现在,当用户编辑 textInput 时,我想识别 textInput 并更新特定索引上的数组文本。
let addMoreCompView = this.state.dataAddMore.map((data ,index) =>{
return(
<View style ={[styles.commonMargin ,{flexDirection : 'row',marginTop : 2 , height : 40, backgroundColor : Globle.COLOR.INPUTCOLOR}]}>
<View style = {{height : '100%' , width : '80%' , justifyContent: 'center' ,alignItems: 'flex-start', flexDirection : 'column'}}>
<TextInput style = {{fontFamily: 'Gotham-Light',fontSize : 14 ,color: Globle.COLOR.BACKCOLOR , paddingLeft : 20}}
underlineColorAndroid = "transparent"
placeholder = 'Please enter emailID.'
placeholderTextColor = 'black'
autoCapitalize = "none"
keyboardType = "email-address"
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleAddMore}
autoCorrect = {false}/>
</View>
<TouchableOpacity onPress = {() => this.removeMoreComponent(data.key)} style = {{height : '90%' , width : '20%' , alignItems: 'flex-end', justifyContent: 'center'}}>
<Image style = {{width : 9 , height : 10 , marginRight : 20}} source = {require('./Images/cancelMore.png')}/>
</TouchableOpacity>
</View>
)
});
这里我想确定是哪个TextInput
调用了这个方法
这里我要textField的文本和索引。
handleAddMore = (text) =>{
// Here I want to text and index of textField.
}
在 textInput 中传递 name
属性。将来如果您需要更新当前状态字段,您可以这样处理:
class MyComponent extends Component {
state = { val1: '', val2: '' };
handleChange = e => this.setState({ [e.target.name]: e.target.value });
render(){
const { val1, val2 } = this.state;
console.log(val1, val2);
return(
<div>
<TextInput
name="val1"
value={val1}
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleChange}
autoCorrect = {false}/>
<TextInput
name="val2"
value={val2}
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleChange}
autoCorrect = {false}/>
</div>
);
}
}
您可以将另一个参数传递给 handleAddMore
?
<TextInput
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {(text) => { this.handleAddMore(text, 'textInput1'); }}
autoCorrect = {false}
/>
handleAddMore = (text, textInput) => {
}
更新 1
onChangeText receives text
as parameter and onChange 收到 event
更新 2
我创建了一个小项目来向您展示它是如何工作的。您可以检查代码并根据需要将其实施到您的项目中。你没有准确地解释错误会让你更难准确地找到你的代码有什么问题。说 不起作用 是永远不够的 。您可以在 Here (Expo)
上找到该项目
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
info: '',
inputCount: 3,
data: [{ name: 'input1' }, { name: 'input2' }, { name: 'input3' }],
};
this.inputRefs = {};
}
onAddMore() {
const newData = this.state.data;
newData.push({ name: `input${this.state.inputCount + 1}` });
this.setState(prevState => ({
inputCount: prevState.inputCount + 1,
data: newData,
}));
}
_onChangeText(text, inputName) {
console.log('Input Name:', inputName, text);
console.log("Inout's Ref:", this.inputRefs[inputName]);
const info = `${this.state.info}\n\r${inputName} changed text`;
this.setState({
info
});
}
_onChange(event, inputName) {
console.log('Input Name:', inputName);
}
render() {
return (
<View style={styles.container}>
{this.state.data.map(d => (
<View style={styles.inputWrapper} key={d.name}>
<TextInput
style={styles.input}
onChangeText={(text) => { this._onChangeText(text, d.name); }}
onChange={(event) => { this._onChange(event, d.name); }}
ref={ref => {
this.inputRefs[d.name] = ref;
}}
defaultValue={d.name}
/>
</View>
))}
<Button
onPress={this.onAddMore.bind(this)}
title="Add More"
color="#841584"
/>
<TextInput
multiline={true}
editable={false}
style={styles.info}>
{this.state.info}
</TextInput>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#F2F2F2',
},
info: {
flex: 0.5,
},
inputWrapper: {
backgroundColor: 'yellow',
marginTop: 5,
marignBottom: 5,
marginLeft: 5,
marginRight: 5,
},
input: {
height: 55,
paddingLeft: 15,
paddingRight: 5,
paddingTop: 5,
paddingBottom: 5,
},
});
下面的代码适用于 React 但不适用于 React Native:“onChangeText”仅传递文本。还有另一种方法称为“onChange”,它传递输入本身,但在本机反应中它不传递输入(因为 RN 适用于 android/iOS/web,而 Android/iOS 没有 event.target)
将 name
添加到 TextInputs
<TextInput
name='input1'
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChange = {(e) => this.handleAddMore(e.target.name)}
autoCorrect = {false}
/>
<TextInput
name='input2'
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChange = {(e) => this.handleAddMore(e.target.name)}
autoCorrect = {false}
/>
并将 handleAddMore 定义为:
handleAddMore = (name) =>{
//add your code here
}
_handleMultiInput(name) {
return (text) => {
this.setState({ [name]:text })
}
}
<TextInput
placeholder='enter your name.'
onChangeText={_handleMultiInput('myName')}
/>
使用功能组件。我要保存三个输入金额、日期和描述。以下是如何将它们保存在单个对象中并对所有三个 TextInput 使用相同的函数。
// useState hook to store object
const [inputValues, setInputValues] = useState({
amount: '',
date: '',
description: '',
});
// will save user input
function inputChangeHandler(inputIdentifier, enteredValue) {
setInputValues(currentInputValues => {
return {
...currentInputValues,
[inputIdentifier]: enteredValue, // dynamically override the desired input
};
});
}
// TextInput Component
<TextInput
onChangeText={inputChangeHandler.bind(this, 'amount')}
value={inputValues.amount}
placeholder={inputValues.title}
/>
<TextInput
onChangeText={inputChangeHandler.bind(this, 'date')}
value={inputValues.date}
placeholder={inputValues.title}
/>
<TextInput
onChangeText={inputChangeHandler.bind(this, 'description')}
value={inputValues.date}
placeholder={inputValues.title}
/>
我已经为 TextInput 创建了通用 class 并多次使用它,但它的事件句柄使用相同的方法。我想在 textInput 中填充数据后处理数组数据。
此处添加了多个 textField 和单个 handleAddMore
。如何识别哪个 textInput 调用了 handleAddMore
.
根据数组数据动态添加的textField组件。现在,当用户编辑 textInput 时,我想识别 textInput 并更新特定索引上的数组文本。
let addMoreCompView = this.state.dataAddMore.map((data ,index) =>{
return(
<View style ={[styles.commonMargin ,{flexDirection : 'row',marginTop : 2 , height : 40, backgroundColor : Globle.COLOR.INPUTCOLOR}]}>
<View style = {{height : '100%' , width : '80%' , justifyContent: 'center' ,alignItems: 'flex-start', flexDirection : 'column'}}>
<TextInput style = {{fontFamily: 'Gotham-Light',fontSize : 14 ,color: Globle.COLOR.BACKCOLOR , paddingLeft : 20}}
underlineColorAndroid = "transparent"
placeholder = 'Please enter emailID.'
placeholderTextColor = 'black'
autoCapitalize = "none"
keyboardType = "email-address"
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleAddMore}
autoCorrect = {false}/>
</View>
<TouchableOpacity onPress = {() => this.removeMoreComponent(data.key)} style = {{height : '90%' , width : '20%' , alignItems: 'flex-end', justifyContent: 'center'}}>
<Image style = {{width : 9 , height : 10 , marginRight : 20}} source = {require('./Images/cancelMore.png')}/>
</TouchableOpacity>
</View>
)
});
这里我想确定是哪个TextInput
调用了这个方法
这里我要textField的文本和索引。
handleAddMore = (text) =>{
// Here I want to text and index of textField.
}
在 textInput 中传递 name
属性。将来如果您需要更新当前状态字段,您可以这样处理:
class MyComponent extends Component {
state = { val1: '', val2: '' };
handleChange = e => this.setState({ [e.target.name]: e.target.value });
render(){
const { val1, val2 } = this.state;
console.log(val1, val2);
return(
<div>
<TextInput
name="val1"
value={val1}
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleChange}
autoCorrect = {false}/>
<TextInput
name="val2"
value={val2}
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {this.handleChange}
autoCorrect = {false}/>
</div>
);
}
}
您可以将另一个参数传递给 handleAddMore
?
<TextInput
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChangeText = {(text) => { this.handleAddMore(text, 'textInput1'); }}
autoCorrect = {false}
/>
handleAddMore = (text, textInput) => {
}
更新 1
onChangeText receives text
as parameter and onChange 收到 event
更新 2
我创建了一个小项目来向您展示它是如何工作的。您可以检查代码并根据需要将其实施到您的项目中。你没有准确地解释错误会让你更难准确地找到你的代码有什么问题。说 不起作用 是永远不够的 。您可以在 Here (Expo)
上找到该项目export default class App extends Component {
constructor(props) {
super(props);
this.state = {
info: '',
inputCount: 3,
data: [{ name: 'input1' }, { name: 'input2' }, { name: 'input3' }],
};
this.inputRefs = {};
}
onAddMore() {
const newData = this.state.data;
newData.push({ name: `input${this.state.inputCount + 1}` });
this.setState(prevState => ({
inputCount: prevState.inputCount + 1,
data: newData,
}));
}
_onChangeText(text, inputName) {
console.log('Input Name:', inputName, text);
console.log("Inout's Ref:", this.inputRefs[inputName]);
const info = `${this.state.info}\n\r${inputName} changed text`;
this.setState({
info
});
}
_onChange(event, inputName) {
console.log('Input Name:', inputName);
}
render() {
return (
<View style={styles.container}>
{this.state.data.map(d => (
<View style={styles.inputWrapper} key={d.name}>
<TextInput
style={styles.input}
onChangeText={(text) => { this._onChangeText(text, d.name); }}
onChange={(event) => { this._onChange(event, d.name); }}
ref={ref => {
this.inputRefs[d.name] = ref;
}}
defaultValue={d.name}
/>
</View>
))}
<Button
onPress={this.onAddMore.bind(this)}
title="Add More"
color="#841584"
/>
<TextInput
multiline={true}
editable={false}
style={styles.info}>
{this.state.info}
</TextInput>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#F2F2F2',
},
info: {
flex: 0.5,
},
inputWrapper: {
backgroundColor: 'yellow',
marginTop: 5,
marignBottom: 5,
marginLeft: 5,
marginRight: 5,
},
input: {
height: 55,
paddingLeft: 15,
paddingRight: 5,
paddingTop: 5,
paddingBottom: 5,
},
});
下面的代码适用于 React 但不适用于 React Native:“onChangeText”仅传递文本。还有另一种方法称为“onChange”,它传递输入本身,但在本机反应中它不传递输入(因为 RN 适用于 android/iOS/web,而 Android/iOS 没有 event.target)
将 name
添加到 TextInputs
<TextInput
name='input1'
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChange = {(e) => this.handleAddMore(e.target.name)}
autoCorrect = {false}
/>
<TextInput
name='input2'
placeholder = 'Please enter emailID.'
onSubmitEditing ={Keyboard.dismiss}
onChange = {(e) => this.handleAddMore(e.target.name)}
autoCorrect = {false}
/>
并将 handleAddMore 定义为:
handleAddMore = (name) =>{
//add your code here
}
_handleMultiInput(name) {
return (text) => {
this.setState({ [name]:text })
}
}
<TextInput
placeholder='enter your name.'
onChangeText={_handleMultiInput('myName')}
/>
使用功能组件。我要保存三个输入金额、日期和描述。以下是如何将它们保存在单个对象中并对所有三个 TextInput 使用相同的函数。
// useState hook to store object
const [inputValues, setInputValues] = useState({
amount: '',
date: '',
description: '',
});
// will save user input
function inputChangeHandler(inputIdentifier, enteredValue) {
setInputValues(currentInputValues => {
return {
...currentInputValues,
[inputIdentifier]: enteredValue, // dynamically override the desired input
};
});
}
// TextInput Component
<TextInput
onChangeText={inputChangeHandler.bind(this, 'amount')}
value={inputValues.amount}
placeholder={inputValues.title}
/>
<TextInput
onChangeText={inputChangeHandler.bind(this, 'date')}
value={inputValues.date}
placeholder={inputValues.title}
/>
<TextInput
onChangeText={inputChangeHandler.bind(this, 'description')}
value={inputValues.date}
placeholder={inputValues.title}
/>