【问题标题】:How can I solve 'Functions are not valid as a React child.' error?如何解决“函数作为 React 子项无效。”错误?
【发布时间】:2020-08-24 15:07:27
【问题描述】:

这是我在下面调用的函数:

const timerDisplay = () => {
        for (var i = 0; i < numbers.length; i++) {
          return (
            <Text>{numbers[i]}</Text>
          )
        }
 }

调用:

<View style={styles.timerTop}>
        <Text style={styles.textTopBot}>{timerDisplay}</Text>
      </View>

所以,当我刷新项目时,它会告诉我“函数作为 React 子级无效”。我该如何解决这个问题?

【问题讨论】:

  • 你没有调用函数
  • 另外,如果您在第一次迭代中返回,通常没有指向 for 循环的意义。
  • 我会说 timerDisplay 并没有做你期望它做的事情。

标签: javascript reactjs function react-native


【解决方案1】:

试试这个关键字

{timerDisplay} --> {this.timerDisplay}

【讨论】:

    【解决方案2】:
    <View style={styles.timerTop}>
        <View style={styles.textTopBot}>
          {numbers.map((number) => <Text>{number}</Text>)}
        </View>
    </View>
    
    【解决方案3】:

    假设您正在使用类组件。

    //函数

    timerDisplay = () => {
                for (var i = 0; i < numbers.length; i++) {
                  return (
                    <Text>{numbers[i]}</Text>
                  )
                }
         }
    

    //调用函数

    <View style={styles.timerTop}>
      <Text style={styles.textTopBot}>{this.timerDisplay}</Text>
    </View>
    

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      相关资源
      最近更新 更多