React - 从孩子身上移除props

IT技术 javascript reactjs
2021-03-27 06:46:23

我需要从孩子身上取下props。

我有一个容器元素,它使用它的子元素的属性来对子元素执行一些增强。在渲染之前,应该从子级中删除该属性。

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

asyncHandler 属性应该在呈现之前从按钮中删除。

AsyncContainer 使用React.cloneElement(child, properties).

我尝试将 asyncHandler 属性置空,将其设置为 undefined 并从 child.props 中删除该属性。看来,想要再摆脱这个属性,是不可能的了。

3个回答

我刚刚遇到了这个问题。您可以创建一个新元素并使用旧元素的类型和要传递的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)
}
这在许多情况下都有效,但有一个缺点。来自文档:reactjs.org/docs/react-api.html#cloneelement "...它也保留了 refs。这意味着如果你得到一个带有 ref 的孩子,你不会意外地从你的祖先那里偷走它。您将获得附加到新元素的相同参考。”
2021-06-09 06:46:23

根据评论,您不能直接修改props,因为它们是不可变的。

但是,我认为我有一个简单的解决方案来解决这个问题。我不知道这是什么库或它是如何工作的,所以这可能会也可能不会但是,这是在安装组件之前如何移除 prop 的一般答案。

话虽如此,我会尝试创建自己的组件来呈现<Button />

class MyButtonComponent extends React.Component {

...

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

然后在您想要增强的组件中:

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

通过这种方式,您可以onClick<Button />组件维护事件侦听器,但不会传递非法asyncHandlerprops。


编辑:

或者,你也可以这样做:

class MyButtonComponent extends React.Component {

...

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

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

这将适用于所有props(与传播经营者),以<Button />除了asyncHandler我们删除之前的零件安装创建的副本propsstate,但与asyncHandler去除。

还要检查这个答案我给了一个类似的问题。

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

怎么运行的

  1. 您可以使用克隆元素,React.cloneElement因为元素是不可变的,更改其props的唯一方法是创建克隆。
  2. 使用第二个React.cloneElement参数添加新props并删除旧props。不需要的props应该用undefined. 您需要这样做,因为默认情况下,克隆元素与其所有props一起被克隆。
你真的测试过这个吗?我认为您不能使用这样的未定义值来替换该函数。我建议看React.createElement()
2021-05-27 06:46:23
这样道具asyncHandler就设置为undefined,但是如何从克隆的组件道具中完全删除?
2021-06-10 06:46:23