最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How could I use a class component inside function component - Stack Overflow

matteradmin5PV0评论

We can use function ponent inside a class ponent, is it possible to do the other way around? For example

class MyClassComponent extends React.Component {
    render() {
        return (
            <p>This is a class ponent with display {this.props.display}</p>
        )
    }
}
const MyFunctionComponent = (props) => {
    return <MyClassComponent display=props.shouldDisplay>This is a function ponent</MyClassComponent >
}

We can use function ponent inside a class ponent, is it possible to do the other way around? For example

class MyClassComponent extends React.Component {
    render() {
        return (
            <p>This is a class ponent with display {this.props.display}</p>
        )
    }
}
const MyFunctionComponent = (props) => {
    return <MyClassComponent display=props.shouldDisplay>This is a function ponent</MyClassComponent >
}
Share Improve this question asked Apr 18, 2020 at 4:51 DrexDrex 3,87110 gold badges46 silver badges77 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 3

React makes it transparent for you whether the ponents you use are functions or classes, so you can pose them as you like.

Specifically in your code there are two issues that you might want to reconsider:

  1. When you define a prop, its value should be wrapped in curly brackets:
<MyClassComponent display={props.shouldDisplay}>
  1. Components can be either self-closing or have children props. In your case, you've added text inside the opening tag and the closing tag, which you can access in MyClassComponent via this.props.children:
const ChildComponent = (props) => {
    return (
        <div>
            {this.props.children}
        </div>
    );
}

const ParentComponent = (props) => {
    return (
        <ChildComponent>
            Hello World
        </ChildComponent>
    );
}

const App = (props) => {
    return <ParentComponent/>;
}
Post a comment

comment list (0)

  1. No comments so far