我如何在函数组件中使用类组件

时间:2020-04-18 04:51:45

标签: javascript reactjs react-hooks

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

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 >
}

1 个答案:

答案 0 :(得分:3)

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

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

  1. 定义道具时,其值应用大括号括起来:
<MyClassComponent display={props.shouldDisplay}>
  1. 组件可以是自动闭合的,也可以有子道具。在您的情况下,您已在开始标签和结束标签中添加了文本,您可以通过MyClassComponentthis.props.children中访问这些文本:
const ChildComponent = (props) => {
    return (
        <div>
            {this.props.children}
        </div>
    );
}

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

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