Reactjs:如何在组件内创建带有参数的函数

Reactjs: How to create a function with args inside a component

在 React 中,有时组件内部有一个函数,当一个项目是 activepressed 时,就像下面的 Pressable 一样。如何重新创建此模式,其中 pressed 变量在函数的 args 中的对象内可用?

<Pressable onPress={ () => null }>
  { ( {pressed} ) => (
    <Text>{pressed ? "Pressed!" : "Press Me"}</Text>
  )
</Pressable>

我的尝试无效

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

const Component = ({ children }) => {
  // Not sure how active should be passed down to children
  // via a useContext maybe? Is that the only way?
  const [active, setActive] = React.useState(true);

  return <View>{children}</View>;
};

export default function App() {
  return (
    <View>
      <Component>
        {({active}) => (
          <Text>
            {active ? "Active" : "Not active"}
          </Text>
        )}
      </Component>
    </View>
  );
}

将命名函数表达式作为子项传递给组件

import { StyleSheet, View, Text } from 'react-native'

const Component = ({ children }) => {

  const [active, setActive] = React.useState(true);

  return <View>{children(active)}</View> ;
};

export default function App() {
  const demo = (active) => (
    <Text>
      {active ? "Active" : "Not active"}
    </Text>
  );
  return (
    <View>
      <Component>
        {demo}
      </Component>
    </View>
  );
}