gpt4 book ai didi

javascript - 在 React 组件中选择内部组件

转载 作者:行者123 更新时间:2023-11-30 07:51:29 24 4
gpt4 key购买 nike

我正在尝试做一个主要组件(在示例中为 Container),它可以容纳一个可选的内部组件,在示例中是硬编码的(条件设置为 true)。

我需要从 React.Component 扩展的内部组件,我不能像函数一样使用它:const ChildOne = (.... )

有 2 个子组件,我们的想法是使用更多。

但是,我不能,我在渲染内部组件时出错了:

Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

class ChildOne extends React.Component {
render() {
return (
<div>
<p> Child One </p>
</div>
)
}
}

class ChildTwo extends React.Component {
render() {
return (
<div>
<p>Child Two</p>
</div>
)
}
}

class Container extends React.Component {
render() {
let condition = true; //Just for testing purpose

let comp = null;
if (condition)
comp = ChildOne;
else
comp = ChildTwo;

return (
<main>
{comp}
</main>
)
}
}

class App extends React.Component {
render() {
return (
<div>
<div><Container /></div>
</div>
)
}
}

https://jsfiddle.net/01L8amgs/

我的想法用完了...提前致谢。

最佳答案

您应该使用大写字母,将 React 自定义组件分配给变量。喜欢Comp = ChildOne;Comp = ChildTwo .. 然后做 <Comp />

来自 User-Defined Components Must Be Capitalized :

When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.

We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

class ChildOne extends React.Component {
render() {
return (
<div>
<p> Child One </p>
</div>
);
}
}

class ChildTwo extends React.Component {
render() {
return (
<div>
<p>Child Two</p>
</div>
);
}
}

class Container extends React.Component {
render() {
let condition = true; //Just for testing purpose

let Comp = null;
if (condition) Comp = ChildOne;
else Comp = ChildTwo;

return (
<main>
<Comp />
</main>
);
}
}

class App extends React.Component {
render() {
return (
<div>
<div>
<Container />
</div>
</div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

关于javascript - 在 React 组件中选择内部组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52235580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com