[英]Reactjs: How to create a function with args inside a component
In React, sometimes components have a function inside it for when an item is active
or pressed
like the Pressable below.在 React 中,有时组件内部有一个 function 用于当项目
active
或pressed
如下面的 Pressable 时。 How can you recreate this pattern where the pressed
variable is available inside an object in the args of a function?如何在 function 的 args 中的
pressed
中重新创建这种模式?
<Pressable onPress={ () => null }>
{ ( {pressed} ) => (
<Text>{pressed ? "Pressed!" : "Press Me"}</Text>
)
</Pressable>
My attempt that doesn't work我的尝试不起作用
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>
);
}
Pass named function expression as a child to the component将命名为 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.