反应组件设置它的子项的点击...如何让它适用于各种孩子



我有一个react组件,它封装另一个组件,并像这样设置子级的onClick

class OutstandingActionForm extends Component {
   render() {
        return (
            <div className="outstanding-actions">
                {React.cloneElement(this.props.children, {onClick : this.openForm})}

它基本上允许父对象(OutstandingActionForm(在子对象(无论是什么(被单击时打开模态,并将单击目标的外观与打开对象的行为分离。

如果子级是<img>:,则此操作正常

           <OutstandingActionForm actions={this.props.actions}>
                <img src={'/assets/notification.jpg'} className="notification-icon"/>
            </OutstandingActionForm>

在这种情况下,如果单击notification.jpg <img>,则会打开OutstandingActionForm

然而,由于某种原因,如果子组件本身就是一个反应组件,它就不起作用:

             <OutstandingActionForm actions={this.props.actions}>
                <OutstandingActionsSummary/>
            </OutstandingActionForm>

即使OustaingActionSummary本身只是一个图像:

class OutstandingActionsSummary extends Component {
    render() {
        return (
              <img src={'/assets/notification.jpg'} className="notification-icon"/>
    )
}

为什么会这样?包装react组件时如何实现与包装本机<img>标签时相同的效果?

<img>知道如何使用onClick。但<OutstandingActionsSummary>没有!在<OutstandingActionsSummary>的实现中,您必须指定如何使用该属性。它应该看起来像:

class OutstandingActionsSummary extends Component {
    render() {
        return <img onClick={this.props.onClick}/>
}
class OutstandingActionsSummary extends Component {
    static defaultProps ={
        onClick:function(){}
    }
    render() {
        return (
              <img onClick={()=>this.props.onClick()} src={'/assets/notification.jpg'} className="notification-icon"/>
    )
}

OutstandingActionsSummary不支持onClick,请添加它。

在OutstandingActionForm中,仅使用{this.props.children}并在Outstanding ActionsSummary上附加单击处理程序,并调用其父OutstandingAction Form进行处理。

最新更新