代码之家  ›  专栏  ›  技术社区  ›  ramanujans alkhazarim

错误“元素类型无效”React Native

  •  0
  • ramanujans alkhazarim  · 技术社区  · 1 年前

    运行此react本机代码会出现错误:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。

        import React from 'react';
    import {Text, Button, View, ScrollView} from 'react';
    
    let id = 0
    
    const Todo = props => (
      <View>
        <Button onPress={props.onDelete} title="delete"/>
        <Text>{props.todo.text}</Text>
      </View>
    )
    
    export default class App extends React.Component {
      constructor() {
        super()
        this.state = {
          todos: [],
        }
      }
    
      addTodo() {
        id++
        const text = `TODO Number ${id}`
        this.setState({
          todos: [
            ...this.state.todos,
            {id: id++, text: text, checked: false},
          ], 
        })
      }
    
      removeTodo(id) {
        this.setState({
          todos: this.state.todos.filter(todo => todo.id !== id)
        })
      }
    
      toggleTodo(id) {
        this.setState({
          todos: this.state.todos.map(todo => {
            if (todo.id !== id) return todo
            return {
              id: todo.id,
              text: todo.text,
              checked: !todo.checked,
            }
          })
        })
      }
    
      render() {
        return (
          <View>
            <Text>Todo count: {this.state.todos.length}</Text>
            <Text>Unchecked todo count: {this.state.todos.filter(todo => !todo.checked).length}</Text>
            <Button onPress={() => this.addTodo()}title="Add TODO"/>
            <ScrollView>
              {this.state.todos.map(todo => (
                <Todo
                  onToggle={() => this.toggleTodo(todo.id)}
                  onDelete={() => this.removeTodo(todo.id)}
                  todo={todo}
                />
              ))}
            </ScrollView>
          </View>
        )
      }
    }

    当我运行这个时,我得到了一个错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。我想是因为出口违约你怎么看?

    1 回复  |  直到 1 年前
        1
  •  0
  •   Braxton Little    1 年前

    问题源于您的第二行代码。您正在从react导入组件,但应该从react native导入它们。代替

    import {Text, Button, View, ScrollView} from 'react';
    

    具有

    import {Text, Button, View, ScrollView} from 'react-native';