繁体   English   中英

我如何在 function 组件中使用 class 组件

[英]How could I use a class component inside function component

我们可以在 class 组件中使用 function 组件,是否可以反过来做? 例如

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

无论您使用的组件是函数还是类,React 都让您透明,因此您可以随意组合它们。

特别是在您的代码中,您可能需要重新考虑两个问题:

  1. 当你定义一个 prop 时,它的值应该用大括号括起来:
<MyClassComponent display={props.shouldDisplay}>
  1. 组件可以是自动关闭的,也可以有子 props。 在您的情况下,您已经在开始标签和结束标签内添加了文本,您可以通过this.props.childrenMyClassComponent中访问它们:
const ChildComponent = (props) => {
    return (
        <div>
            {this.props.children}
        </div>
    );
}

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

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

暂无
暂无

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

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