2017-03-27 137 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) 
}