繁体   English   中英

如何在 React Native 中从另一个功能组件更改一个功能组件的状态?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM