[英]How to call a change a state in a component using a button function from another component In React?
[英]How to change state of one function component from another function component in React Native?
我是 React Native 和 JavaScript 的新手。 我想在单击按钮时更新文本。 我阅读了其他问题,但主要是关于类组件。 下面是我的代码。
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;
注意:我知道我可以在 Playground 组件中创建 Button,但我想知道如何从另一个组件或另一个组件(如onPress
某些事件更改状态。
试试这个方法
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.