[英]Reactjs: How to create a function with args inside a component
在 React 中,有时组件内部有一个 function 用于当项目active
或pressed
如下面的 Pressable 时。 如何在 function 的 args 中的pressed
中重新创建这种模式?
<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>
);
}
将命名为 function 的表达式作为子组件传递给组件
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.