繁体   English   中英

如何在reactjs中使用高阶组件添加按钮

[英]How to add a button using Higher Order Component in reactjs

如何使用高阶组件向组件添加按钮? 我试过这个,但它没有在组件内添加按钮。 它在原始组件之前添加它。

const withButton = WrappedComponent => {
  return class extends Component {
    render() {
      return (
        <Fragment>
          <button>BUTTON ADDED USING HOC</button>
          <WrappedComponent {...this.props} />
        </Fragment>
      )
    }
  }
}
export default withButton

当我这样打电话给HOF时

const ComponentWithButton = withButton(WrappedComponent)

ComponentWithButton添加了按钮,但它在WrappedComponent之前添加,而我想在内部添加按钮作为WrappedComponent的子项。

让我们说WrappedComponent正在呈现类似的东西

<div className="baseClass">{other divs and layout}</div>

const ComponentWithButton = withButton(WrappedComponent)

ComponentWithButton应呈现以下内容

<div className="baseClass">
<button>BUTTON ADDED USING HOC</button>
{other divs and layout}
</div>

如果要将按钮动态放置在WrappedComponent内的某个位置,可以尝试这样的操作。

const withButton = WrappedComponent => {
  return class extends Component {
    render() {
      return (
        <Fragment>
          <WrappedComponent {...this.props}>
            <button>BUTTON ADDED USING HOC</button>
          </WrappedCompnent>
        </Fragment>
      )
    }
  }
}
export default withButton

现在,在您的包装组件中,您可以将按钮放在任何您想要的位置,因为该按钮可以作为WrappedComponent的属性子项访问。

const WrappedComponent = ({ children, ...otherProps }) => (
  <div className="baseClass">
    {children}
    {renderOtherDivsAndProps(otherProps)}
  </div>
);

希望这对你有所帮助

尝试使用props.children ,也可以参考React.Children API

function ComponentWithButton({ children }) {
  return (
    <>
      <button>BUTTON ADDED USING HOC</button>
      {children}
    </>
  );
}

然后渲染:

<ComponentWithButton>
  <WrappedComponent />
</ComponentWithButton>

有课程:

class ComponentWithButton extends Component {
  render() {
    const { children } = this.props;
    return (
      <>
        <button>BUTTON ADDED USING HOC</button>
        {children}
      </>
    );
  }
}
export default ComponentWithButton;

我试过这个,我正在寻找我正在寻找的东西。

const withButton = WrappedComponent => {
  return class extends Component {
    render() {
      return (
          <WrappedComponent {...this.props}>
            <button>BUTTON ADDED USING HOC</button>
            {this.props.children}
          </Wrappedcomponent>
      )
    }
  }
}
export default withButton

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM