在 React Native 中使用文本输入按下按钮后如何更改组件的状态?
how do i change the state of a component after a button is pressed using text input in react native?
这会在我打字时改变状态,但我希望初始状态保持不变,只有在完成文本输入并按下按钮后,状态才会改变
import {View, Text, StyleSheet, Button, TextInput} from 'react-native';
export default function app() {
const [normal, setname] = useState('arun');
const submithandler = val => {
setname(val);
};
return (
<View style={Styles.container}>
<Text>hi {normal}</Text>
<TextInput style={Styles.Text} onChangeText={val => submithandler(val)} />
</View>
);
}
const Styles = StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
Text: {
borderBottomColor: 'black',
borderWidth: 1,
width: 400,
marginVertical: 20,
},
});```
**i want the value to be changed only after clicking the button**
您可以使用 2 个状态:
const [textValue, setTextValue] = useState('arun');
const [name, setName] = useState('arun');
...
<Text>hi {name}</Text>
<TextInput
value={textValue}
onChangeText={val => setTextValue(val)}
/>
<Button
onPress={() => setName(textValue)}
title="Submit"
/>
这会在我打字时改变状态,但我希望初始状态保持不变,只有在完成文本输入并按下按钮后,状态才会改变
import {View, Text, StyleSheet, Button, TextInput} from 'react-native';
export default function app() {
const [normal, setname] = useState('arun');
const submithandler = val => {
setname(val);
};
return (
<View style={Styles.container}>
<Text>hi {normal}</Text>
<TextInput style={Styles.Text} onChangeText={val => submithandler(val)} />
</View>
);
}
const Styles = StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
Text: {
borderBottomColor: 'black',
borderWidth: 1,
width: 400,
marginVertical: 20,
},
});```
**i want the value to be changed only after clicking the button**
您可以使用 2 个状态:
const [textValue, setTextValue] = useState('arun');
const [name, setName] = useState('arun');
...
<Text>hi {name}</Text>
<TextInput
value={textValue}
onChangeText={val => setTextValue(val)}
/>
<Button
onPress={() => setName(textValue)}
title="Submit"
/>