【问题标题】:How to Display different Components on selection options from Dropdown menu using React js如何使用 React js 在下拉菜单中的选择选项上显示不同的组件
【发布时间】:2020-01-17 12:37:46
【问题描述】:

我是 React js 的新手,任何帮助将不胜感激。 我想要的是在下拉菜单中选择不同选项时显示具有不同文本的不同组件。

我可以使用 {this.state.value} 显示价值,但这不是我想要的。 这是我现有代码的链接。

https://codesandbox.io/s/nifty-noyce-cj466

【问题讨论】:

  • 你想展示哪些组件可以举个例子
  • 我已经更新了我的代码。假设如果你点击 python 一个组件名称 python 应该用 python 显示文本,同样的 android 应该显示名为 android 的组件应该用 android 显示文本。

标签: reactjs react-router react-dropdown-tree-select


【解决方案1】:

您好,欢迎来到 SO =)

如果你想根据某些条件渲染不同的组件,那么你可以做这样的事情:

{item === "first" && <Component1 />}
{item === "second" && <Component2 />}
{item === "third" && <Component3 />}

您可以在此处找到有关条件渲染的更多信息:https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

这里是 Dan Abramov 的一篇关于和解的精彩文章:https://overreacted.io/react-as-a-ui-runtime/#reconciliation

【讨论】:

  • 感谢@Ivan 的回答。它解决了我的疑问。
  • 我很高兴为您提供帮助 =)
  • “所以更好(性能)的方法是使用三元运算符”你确定这是真的吗?
  • @DennisVash,你说得对! React 将null 置于这种结构{item === "first" &amp;&amp; &lt;Component1 /&gt;} 的底层。我编辑我的答案,谢谢!
【解决方案2】:

其他人已经指出了如果你只有几个组件如何动态渲染组件,但如果你有很多组件,你可能希望将它们存储在字典中:

const Android = () => (
  <span>android</span>
);

const Python = () => (
  <span>python</span>
);

const components = {
  "android": Android,
  "python": Python,
};

const Main = () => {
  // choose here based on a key
  const Component = components['android'];
  return (
    <React.Fragment>
      <Component/>
    </React.Fragment>
  );
};

【讨论】:

    【解决方案3】:

    根据变量或状态显示不同组件的最简单方法之一是使用内联条件渲染。您可以尝试以下方法:

    {this.state.value === "test" ? <Component1 />: <Component2 />}
    

    您还可以将this.state.value 作为属性传递给另一个组件,该组件有条件地呈现其他元素(或组件)。如果你是新手,你真的应该阅读一些基本的反应教程,因为这是其中的一部分 - see examples

    【讨论】:

    • 如果我有超过 2 个组件怎么办
    • 你打开我给你答案的链接了吗?还有一个 if-else 的例子。你可以使用 if(test1) {res = } else if(test2) {res = } else if(test3) {res = } ... 甚至是一个开关,如果你'想要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多