如何在 React Native 中从另一个功能组件更改一个功能组件的状态?
How to change state of one function component from another function component in React Native?
我是 React Native 的新手 JavaScript。我想在单击按钮时更新文本。我阅读了其他问题,但主要是关于 class 组件。下面是我的代码。
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;
我是 React Native 的新手 JavaScript。我想在单击按钮时更新文本。我阅读了其他问题,但主要是关于 class 组件。下面是我的代码。
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;