[英]React Native: Passing value from <TextInput> into a function declared outside of a component
I am currently building a component that includes a <TextInput
which captures a value called userInput
.我目前正在构建一个包含<TextInput
的组件,该组件捕获一个名为userInput
的值。 I have a <TouchableOpacity>
which then invokes a function which is declared outside of the component, however this particular function accepts the userInput
as one of it's arguments.我有一个<TouchableOpacity>
然后调用一个在组件外部声明的 function,但是这个特定的 function 接受userInput
作为它的 ZDBC11CAA5BDA99F77E6FB4DABD882E 之一。
I am struggling to figure out how to use the value assigned to userInput
in the component's state, and pass it to myFunction
.我正在努力弄清楚如何在组件的 state 中使用分配给userInput
的值,并将其传递给myFunction
。 Is this possible and/or is there a better way to achieve this?这是否可能和/或有更好的方法来实现这一目标?
I did try moving the function inside the component, however this caused errors with the function.我确实尝试在组件内移动 function,但这会导致 function 出现错误。
Any help would be very much appreciated.任何帮助将不胜感激。
import React, {Component} from 'react';
import {Text, View} from 'react-native';
import {TextInput} from 'react-native-gesture-handler';
const myFunction = () => {
func()
.then(async user => {
const userInput = this.state.userInput;
await addToProfile(user, userInput);
})
.catch(err => {
console.error(err);
});
};
export default class Stackoverflow extends Component {
state = {
userInput: '',
};
constructor(props) {
super(props);
this.textInputComponent = React.createRef();
}
render() {
return (
<View>
<TextInput
ref={this.textInputComponent}
keyboardAppearance={'dark'}
value={this.state.userInput}
onChangeText={value => this.setState({userInput: value})}
/>
<TouchableOpacity
onPress={() => {
myFunction();
}}
/>
</View>
);
}
}
TouchableOpacity should have some child component within it to touch. TouchableOpacity 应该有一些子组件可以触摸。
Lets take an example:举个例子:
const callme= () => {
console.log("Pressed event called.....");
};
const mycomponent = () => {
return (
<TouchableItem
onPress={() => {
callme();
}}
useOpacity
>
<View style={[styles.container]}>
<Text style={[styles.mytextstyle}>Some title here</Text>
</View>
</TouchableItem>
);
};
I managed to solve the issue my moving the function declaration into the onPress()
of the TouchableOpacity
我设法解决了将 function 声明移动到TouchableOpacity
的onPress()
的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.