簡體   English   中英

反應-從孩子身上移除道具

[英]React - Remove prop from child

我需要從孩子身上移除道具。

我有一個容器元素,該元素使用子元素上的屬性對子元素進行一些增強。 在渲染之前,應從子級中刪除該屬性。

<AsyncContainer>
   <Button onClick={this.asyncStuff} asyncHandler="onClick"/>
</AsyncContainer>

呈現之前,應從按鈕中刪除asyncHandler屬性。

AsyncContainer使用React.cloneElement(child, properties)

我嘗試將asyncHandler屬性設置為空,將其設置為undefined,然后從child.props中刪除該屬性。 似乎不可能再次擺脫此屬性。

我剛遇到這個問題。 您可以只創建一個新元素,並使用舊元素的類型和要傳遞的道具。 我不確定這是否是反模式,我偶然發現了它,到目前為止它似乎運行良好。

它看起來應該像這樣:

function AsyncContainer(props) {
  const child = React.Children.only(props.children)
  const { asyncHandler, ...childProps } = child.props
  // do asyncHandler stuff
  return React.createElement(child.type, childProps)
}

根據評論,您不能直接修改道具,因為它們是不可變的。

但是,我認為我對此問題有一個簡單的解決方案。 我不知道它是什么庫或它是如何工作的,所以這可能會或可能不會 但是,這是在安裝組件之前如何移除支撐的一般答案。

話雖如此,我會嘗試創建自己的呈現<Button />的組件:

class MyButtonComponent extends React.Component {

...

  render() {
    return <Button onClick={this.props.onClickHandler} />;
  }
}

然后在組件中進行增強:

render() {
  <AsyncContainer>
    <MyButtonComponent onClickHandler={this.asyncStuff} asyncHandler="onClick"/>
  </AsyncContainer>
}

這樣,您可以在<Button />組件上維護onClick asyncHandler但不會傳遞非法的asyncHandler


編輯:

或者,您也可以執行以下操作:

class MyButtonComponent extends React.Component {

...

  componentWillMount() {
    let newProps = this.props;
    delete newProps.asyncHandler;
    this.setState({properties: newProps}):
  }

  render() {
    return <Button {...this.state.properties} />;
  }
}

這會將所有道具(使用spread操作符 )應用於<Button />asyncHandler除外,我們通過在state下創建props的副本但移除了asyncHandler方式在組件安裝之前將其刪除。

還要檢查我給類似問題的答案

function AsyncContainer(props) {
  const child = React.Children.only(props.children);
  return React.cloneElement(
    child,
    { asyncHandler: undefined }
  );
}

這個怎么運作

  1. 您使用React.cloneElement克隆元素,因為element是不可變的,更改道具的唯一方法是創建克隆。
  2. 使用第二個React.cloneElement參數添加新道具並刪除舊道具。 不需要的道具應該分配undefined 您需要執行此操作,因為默認情況下,cloned元素會與其所有props一起被克隆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM