簡體   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