我试图做一个主要组件(在示例中,容器),它可以保持内部组件可选,在示例中是harcoded(条件设置为true) .
我需要从React.Component扩展内部组件,我不能像函数一样使用它: const ChildOne = (.... )
有2个子组件,想法是使用更多 .
但是,我不能,我在渲染内部组件时遇到错误:
函数作为React子函数无效 . 如果返回Component而不是render,则可能会发生这种情况 . 或许你打算调用这个函数而不是返回它 .
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/
我的想法用完了......先谢谢了 .
2 回答
您应该使用大写字母,将React自定义组件分配给变量 . 喜欢
Comp = ChildOne;
或Comp = ChildTwo
..那就做<Comp />
来自User-Defined Components Must Be Capitalized:
您需要使用正确的语法呈现组件:
<Comp>
而不是{comp}
这是一个工作示例:https://jsfiddle.net/01L8amgs/2/
请注意,为此更改了Container类的呈现函数