我是 React js 的新手,任何帮助将不胜感激。我想要的是在下拉菜单中选择不同选项时显示具有不同文本的不同组件。
我可以使用 {this.state.value} 显示价值,但这不是我想要的。这是我现有代码的链接。
我是 React js 的新手,任何帮助将不胜感激。我想要的是在下拉菜单中选择不同选项时显示具有不同文本的不同组件。
我可以使用 {this.state.value} 显示价值,但这不是我想要的。这是我现有代码的链接。
其他人已经指出了如果你只有几个组件如何动态渲染组件,但如果你有很多组件,你可能希望将它们存储在字典中:
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>
);
};
嗨,欢迎来到 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
根据变量或状态显示不同组件的最简单方法之一是使用内联条件渲染。您可以尝试以下方法:
{this.state.value === "test" ? <Component1 />: <Component2 />}
您还可以将this.state.value属性作为属性传递给另一个组件,该组件有条件地呈现其他元素(或组件)。如果您是新手,那么您真的应该阅读一些基本的反应教程,因为这是其中的一部分 -请参阅示例