【问题标题】:How can i make component accepts elements inside?我怎样才能让组件接受里面的元素?
【发布时间】:2022-01-16 17:01:12
【问题描述】:

我想制作一个组件,但我希望它也接受元素。例如:

组件:

const Example = () => {

    return (
        <div>
            //Some Elements will come here.
        </div>
    )
}

另一页:

const App = () => {

    return (
        <Example>
            <div>
                <h1>Hello all </h1>
                <p>I want that elements acceptable on my custom component </p>
            </div>
        </Example>
    )
}

但我只能发送道具,我不能在我的组件标签内写任何东西。我怎样才能做到?谢谢大家!

【问题讨论】:

  • “我不能在我的组件的标签内写任何东西”是什么意思

标签: javascript html reactjs


【解决方案1】:

React 定义了一个名为 children 的特殊属性。这正是您所需要的。

这样试试

const Example = ({ children }) => {
    return <div>{children}</div>;
};

const App = () => {
    return (
        <Example>
            <div>
                <h1>Hello all </h1>
                <p>I want that elements acceptable on my custom component </p>
            </div>
        </Example>
    );
};

【讨论】:

  • 谢谢!成功了!
【解决方案2】:

您可以使用props.children

const Example = props => {
    return <div>{props.children}</div>;
};

【讨论】:

  • 谢谢!!它对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多