I am new to React Native and JavaScript. I want to update Text on click of button. I read other questions but mostly they are about class components. Here's my code below.
import React, { useState } from 'react';
import { View, Text, Button} from 'react-native';
const Playground = () => {
const [count, setCount] = useState(0);
return (
<View style={{ padding: 5 }}>
<Text style={{ fontSize: 26 }}>
Tap count = {count}.
</Text>
<TapButton />
</View>
);
}
const TapButton = () => {
return (
<Button
title="Hit" />
);
}
export default Playground;
Note: I know I can create Button in Playground component, But I want to know how to change state from another component or some event in another component like onPress
.
Try this way
const Playground = () => {
const [count, setCount] = useState(0);
return (
<View style={{ padding: 5 }}>
...
// send `onCountPress` as prop
<TapButton count={count} onCountPress={setCount}/>
</View>
);
}
const TapButton = ({count, onCountPress}) => {
return (
<Button
...
onPress={onCountPress(count + 1)} // update here
/>
);
}
export default Playground;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.