2017-03-27 138 views
1

我需要從兒童中刪除道具。反應 - 從兒童中刪除道具

我有一個容器元素,它使用它的孩子的屬性來對孩子進行一些增強。在渲染前應該將該屬性從小孩中移除。

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

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

AsyncContainer使用React.cloneElement(child, properties)

我已經嘗試nulling asyncHandler屬性,將其設置爲undefined並從child.props刪除屬性。似乎不可能再次擺脫這個屬性。

+0

'props',因此不能由組件自身來改變。父母必須修改'prop',然後將其傳遞給組件。 – Dan

+0

你不能對兒童道具做任何事情,因爲它們是隻讀的:https://facebook.github。io/react/docs/components-and-props.html#props-are-read-only –

+0

也許你可以克隆孩子並以某種方式替換屬性對象? – AnAmuser

回答

0

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

但是,我想我有一個簡單的解決方案來解決這個問題。我不知道什麼庫是或它如何工作,所以這可能會或可能不會工作。但是,這是一個普通的答案,你可以在組件裝入之前刪除一個道具。

話雖這麼說,我會嘗試創建自己的組件,它呈現一個<Button />

class MyButtonComponent extends React.Component { 

... 

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

然後在你想要做你的增強組件:

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

這樣你保持您的onClick eventlistener上的<Button />組件,但您不通過非法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 operator)適用於<Button />除了asyncHandler我們刪除之前通過在state中創建props的副本來安裝該組件,但會刪除asyncHandler

也檢查this answer我給了一個類似的問題。

2

我剛碰到這個問題。你可以創建一個新元素,並使用舊元素的類型和道具來通過。我不確定這是否是一種反模式,我只是偶然發現它,而且目前看起來效果不錯。

它應該是這個樣子:在陣營是不可改變的

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