Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

How to properly implement custom components in React Native in their own file?

I've moved my code of a custom React Native component to it's own file such as this:

import React from 'react';
import { StyleSheet, Text, View } from "react-native";

export default class MyButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Text style={{fontSize: 20, color: "#008000"}}>Foo Bar</Text>
        );
    };
};

In App.js I can refer to that file that contains that code. The framework does not complain:

import { MyButton } from "./MyButton";

But as soon as I include MyButton in the App rendering function I receive the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

The rest of the error message is completely useless.

I did some searches on the web to learn what could have caused that error. But none of all hints I found seemed to be related to my case here. For example I use import React from 'react'; which is advised by some answers even here on stack overflow, but still this doesn't work. (See: Custom component undefined in React Native)

If I move the code to App.js everything works fine. If I move it to another file things don't work. What do I need to change in that file in order to successfully have a component in that file? And include that in similar way as those native components in my App.js?

Thank you for your help!

question from:https://stackoverflow.com/questions/65910848/how-to-properly-implement-custom-components-in-react-native-in-their-own-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your import statement is incorrect.

import { MyButton } from "./MyButton";

This import statement imports a named export called MyButton from the ./MyButton module. However, in your MyButton file you are default exporting the MyButton component. What you want to do is:

import MyButton from "./MyButton";

which imports whatever is exported by default from the module, in this case the MyButton component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...