【问题标题】:How can I remove a component using the children prop in React如何使用 React 中的 children 属性删除组件
【发布时间】:2018-01-04 05:06:26
【问题描述】:

我正在尝试实现这种情况:

  1. 我有 Foo 组件bar prop

  2. 如果 bar prop 为 true --> mount Bar 组件 位于 Foo 组件内

  3. 如果 bar 属性为 false --> 卸载 Bar 组件
  4. 我不想让示例组件知道这个显示/隐藏,我只想让 Foo 知道何时显示或隐藏它
  5. Bar 不一定是 Foo 的直接子级,它也可以嵌套在 Foo 的子级中更深
const Example = () => {
  return (
    <Foo bar={true/false}>
      <div>some div</div>
      <Bar></Bar>
    </Foo>
  )
};

class Foo extends React.Component {

  componentWillReceiveProps({bar}) {
    if (bar) {
      /* I want to show bar!! */
    } else {
      /* I want to remove only bar!! */
      /* maybe doing something like: this.props.children.searchForBar().removeNode() */
    }
  }

  render () {
    return (
      <div>{this.props.children}</div>
    )
  }
};

const Bar = () => 'I am some bar';

我试图操纵 this.props.children 但 React 阻止我自己修改孩子。

这两个组件之间的通信是否需要外部服务?

我应该使用上下文吗?

寻求有关如何解决此问题的建议。

【问题讨论】:

  • 是的,如果你想切换 即使 不是 的孩子,你也需要外部的东西来处理状态(比如 redux)

标签: javascript reactjs jsx


【解决方案1】:

一个简单的解决方案是在Foo component 内部使用Bar component,并基于ternary condition 进行渲染。

还返回一个 JSX 元素(来自 Bar 组件的有效反应元素)而不是字符串。

const Example = () => {
  return (
    <Foo bar={true}>
      <div>some div</div>
    </Foo>
   
  )
};

class Foo extends React.Component {

  
  render () {
    return (
      <div>
        <div>{this.props.children}</div>
        {this.props.bar? <Bar />: null}
      </div>
    )
  }
};

const Bar = () => <div>I am some bar</div>;

ReactDOM.render(<Example/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

【讨论】:

  • 我正在尝试将 Bar 嵌套在 Foo 之外。我基本上是想了解一个组件如何具有它可以知道的“子组件”。所以 Foo 是主要组件,但它可以“控制”像 Bar 这样的子组件并隐藏它,即使 Bar 不在 Foo 内
【解决方案2】:

一种可能的解决方案是使用某种消息总线或 pubSub。在这种方法中,Bar 组件必须订阅总线,并显示/隐藏自己。 Foo 组件将在 componentWillReceiveProps 中发布适当的消息。更多:here

【讨论】:

    猜你喜欢
    • 2015-12-29
    • 2018-07-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2017-11-27
    • 2021-02-26
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多