如何使用 React js 在下拉菜单中的选择选项上显示不同的组件
How to Display different Components on selection options from Dropdown menu using React js
我是 React js 的新手,我们将不胜感激。
我想要的是在下拉菜单中选择不同的选项时显示具有不同文本的不同组件。
我可以使用 {this.state.value} 显示值,但这不是我想要的。
这是我现有代码的 link。
根据变量或状态显示不同组件的最简单方法之一是使用内联条件渲染。您可以尝试类似的操作:
{this.state.value === "test" ? <Component1 />: <Component2 />}
您还可以将 this.state.value
作为 属性 传递给另一个有条件地呈现其他元素(或组件)的组件。如果你是新手,你真的应该学习一些基本的 React 教程,因为这是其中的一部分 - see examples
您好,欢迎来到 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
其他人已经指出了如果你只有几个组件如何动态渲染组件,但如果你有很多组件你可能想将它们存储在字典中:
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>
);
};
我是 React js 的新手,我们将不胜感激。 我想要的是在下拉菜单中选择不同的选项时显示具有不同文本的不同组件。
我可以使用 {this.state.value} 显示值,但这不是我想要的。 这是我现有代码的 link。
根据变量或状态显示不同组件的最简单方法之一是使用内联条件渲染。您可以尝试类似的操作:
{this.state.value === "test" ? <Component1 />: <Component2 />}
您还可以将 this.state.value
作为 属性 传递给另一个有条件地呈现其他元素(或组件)的组件。如果你是新手,你真的应该学习一些基本的 React 教程,因为这是其中的一部分 - see examples
您好,欢迎来到 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
其他人已经指出了如果你只有几个组件如何动态渲染组件,但如果你有很多组件你可能想将它们存储在字典中:
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>
);
};