将 react const 渲染为组件
render react const as component
假设我有这个父
const Parent = () => <ChildComponent foo={<Button>clic</Button>} />
为什么这段代码可以工作
class ChildComponent extends React.Component {
render() {
return (
<div>
{this.props.foo}
</div>
)
}
}
但是这段代码不会?
class ChildComponent extends React.Component {
constructor(props) {
super(props)
const ParentButton = this.props.foo
}
render() {
return (
<div>
<ParentButton />
</div>
)
}
}
我需要类似于第二个示例的东西,以便向 ParentButton 添加一些事件。
我想让 与 class 定义的组件一起工作
更新:
根据答案我现在有了部分解决方案
class ChildComponent extends React.Component {
constructor(props) {
super(props)
this.ParentButton = this.props.foo
}
render() {
return (
<div>
{this.ParentButton}
</div>
)
}
}
您没有将 ParentButton
分配给 ChildComponent
。
您当前拥有的是 const
浮动在构造函数中,因为 const
、let
和 var
关键字是 function/block 范围的。
this. ParentButton = this.props.foo
并在您的渲染函数中简洁地 <this. ParentButton >
将为您提供所需的内容。
假设我有这个父
const Parent = () => <ChildComponent foo={<Button>clic</Button>} />
为什么这段代码可以工作
class ChildComponent extends React.Component {
render() {
return (
<div>
{this.props.foo}
</div>
)
}
}
但是这段代码不会?
class ChildComponent extends React.Component {
constructor(props) {
super(props)
const ParentButton = this.props.foo
}
render() {
return (
<div>
<ParentButton />
</div>
)
}
}
我需要类似于第二个示例的东西,以便向 ParentButton 添加一些事件。
我想让
更新:
根据答案我现在有了部分解决方案
class ChildComponent extends React.Component {
constructor(props) {
super(props)
this.ParentButton = this.props.foo
}
render() {
return (
<div>
{this.ParentButton}
</div>
)
}
}
您没有将 ParentButton
分配给 ChildComponent
。
您当前拥有的是 const
浮动在构造函数中,因为 const
、let
和 var
关键字是 function/block 范围的。
this. ParentButton = this.props.foo
并在您的渲染函数中简洁地 <this. ParentButton >
将为您提供所需的内容。