I have a component like below based on Hooks
import React, { useEffect, useState } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Animated
} from 'react-native';
import CAStyles from '../res/CAStyles';
const CACard = (props ) => (
<TouchableOpacity onPress={props.cardTouched}>
<View style={[styles.cardContainer, CAStyles.ALIGN_CENTER]} width={props.width} height={props.height}>
<Text style={styles.textStyle}>{props.title}</Text>
</View>
</TouchableOpacity>
);
export default CACard
I'd like to have own state values and functions inside the hook. But it is throwing syntax error. I know it is possible with Class based components but not sure why it is not possible with Hooks.
My subsequent attempts to find a solution is futile. Can someone help me out here. Thanks in advance.
Thanks to @JMadelaine for pointing it out. I changed as below and it all works fine.
const CACard = (props ) => {
return (
<TouchableOpacity onPress={props.cardTouched}>
<View style={[styles.cardContainer, CAStyles.ALIGN_CENTER]} width={props.width} height={props.height}>
<Text style={styles.textStyle}>{props.title}</Text>
</View>
</TouchableOpacity>
)
};
As JMadelaine correctly pointed out. You need to write useState inside functional component definition. Restructure your code like this:
import React, { useEffect, useState } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Animated
} from 'react-native';
import CAStyles from '../res/CAStyles';
const CACard = (props) =>{
const [aStateVar, setAStateVar] = useState(false);
return (
<TouchableOpacity onPress={props.cardTouched}>
<View style={[styles.cardContainer, CAStyles.ALIGN_CENTER]} width={props.width} height={props.height}>
<Text style={styles.textStyle}>{props.title}</Text>
</View>
</TouchableOpacity>
);
};
export default CACard;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.