繁体   English   中英

可以在 React 钩子内调用 function

[英]Call a function inside a React hook is possible

我有一个基于 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

我想在钩子中有自己的 state 值和函数。 但它抛出语法错误。 我知道基于 Class 的组件是可能的,但不确定为什么 Hooks 不可能。

我随后寻找解决方案的尝试是徒劳的。 有人可以帮我吗? 提前致谢。

感谢@JMadelaine 指出这一点。 我进行了如下更改,一切正常。

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>
  )
    
};

正如 JMadelaine 正确指出的那样。 您需要在功能组件定义中编写 useState 。 像这样重构你的代码:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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