ReactJs:如何创建一个包装器组件,该组件将在单击时执行某些代码并呈现子组件



我正在尝试创建一个通用的React组件,我可以将其封装在任何组件上,并在单击时执行一些代码:

class WrapperComponent extends React.Component {
constructor() {
super();
this.state = {};
this.onElementClicked = this.onElementClicked.bind(this);
}
onElementClicked() {
// CODE TO BE EXECUTED WHEN WRAPPER ELEMENT IS LICKED
}
render() {
const {child_component}=this.props
return (
<span
onClick={() => {
this.onElementClicked();
}}
>
{child_component}
</span>
);
}
}

我会这样使用它:

<WrapperComponent
component={<Button>Test</Button>}
></WrapperComponent>

这非常好用
但是,我觉得采用这种方法是不对的。这就是我想要实现的目标:

<WrapperComponent>
<Button>Test</Button>
</WrapperComponent>

因此,我所要做的就是用WrapperComponent包装我想要的任何元素,并获得相同的结果
有可能吗?

你在找这样的东西吗?https://reactjs.org/docs/composition-vs-inheritance.html

您可能可以使用props.children 访问子组件

相关内容

最新更新