I have an input, text and button component. I want to change the text value with input value when button is clicked.
I searched on stackoverflow but they only change text after input text is change by using onChangeText prop of textinput.
CodePudding user response:
Use
onPress
prop of the button component. This prop takes a function that will be called when the button is clicked.
In that function, you can use the setState method to update the state of your component with the new text value from the input. This will trigger a re-render of your component and update the text value.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
textValue: '',
};
}
onButtonPress = () => {
const { inputValue } = this.state;
this.setState({
textValue: inputValue,
});
}
render() {
const { textValue } = this.state;
return (
<View>
<TextInput
value={inputValue}
onChangeText={inputValue => this.setState({ inputValue })}
/>
<Button onPress={this.onButtonPress} title="Update Text" />
<Text>{textValue}</Text>
</View>
);
}
}
onButtonPress function is called when the button is clicked and it updates the textValue state with the current inputValue, which update text with the new value assigned.
CodePudding user response:
To change the text value of a Text component based on the value of an Input component when a Button is clicked, you can use the onPress
prop of the Button
component to define an event handler that updates the text value of the Text component.
Here is an example (NOTE: just a sample - you didn't provide a code on which I could base it) of how you could do this:
import React from 'react';
import { Button, Input, Text } from 'react-native';
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
textValue: '',
};
}
handleInputChange = (inputValue) => {
this.setState({ inputValue });
}
handleButtonPress = () => {
this.setState({ textValue: this.state.inputValue });
}
render() {
return (
<>
<Input
value={this.state.inputValue}
onChangeText={this.handleInputChange}
/>
<Button
title="Update text"
onPress={this.handleButtonPress}
/>
<Text>{this.state.textValue}</Text>
</>
);
}
}
In this example, the MyApp
component maintains the state of the input value and the text value. The handleInputChange
event handler is called when the value of the Input component changes, and updates the input value in the component's state. The handleButtonPress
event handler is called when the Button
is pressed, and updates the text value in the component's state with the current input value. Finally, the Text component is rendered with the current text value from the component's state.
By using the onChangeText
and onPress
props to define event handlers that update the component's state, you can control the text value of a Text component based on the value of an Input component.