我有以下代码只是为了模拟我的问题。我想在按钮单击时有条件地渲染组件。这是我的代码,如何使用功能和开关盒有条件地渲染组件。请记住,我只使用功能组件,而不使用类组件。
import React from "react";
import ReactDOM from "react-dom";
import One from "./One";
import Two from "./Two";
import Three from "./Three";
import None from "./None";
import "./styles.css";
const handleRender = (e, props) => {
let exp = Math.floor(Math.random() * props);
console.log(exp);
return exp;
};
function Test(exp) {
switch (exp) {
case 1:
return <One />;
case 2:
return <Two />;
case 3:
return <Three />;
default:
return <None />;
}
}
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={(e, p) => handleRender("a", "5")}>
Render One Two or Three
</button>
<Test />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
答案 0 :(得分:1)
您可以通过下面的App功能实现所需的功能
function App() {
const [state, setState] = React.useState(null)
const testNode = Test(state)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={(e, p) => setState(handleRender("a", "5"))}>
Render One Two or Three
</button>
{testNode}
</div>
);
}
但是,我不建议这种方法用于此类任务
答案 1 :(得分:1)
您需要添加状态:
const handleRender = (e, props) => {
let exp = Math.floor(Math.random() * props);
console.log(exp);
return exp;
};
function Test(exp) {
switch (exp) {
case 1:
return <One />;
case 2:
return <Two />;
case 3:
return <Three />;
default:
return <None />;
}
}
function App() {
const [exp, setExp] = useState(0);
return (
<div className="App">
<button onClick={() => setExp(handleRender('a', '5'))}>
Render One Two or Three
</button>
{Test(exp)}
</div>
);
}
答案 2 :(得分:1)
您可以使用挂钩来跟踪点击,然后有条件地进行渲染。
例如:
import React, { useState } from "react";
// Your other imports.
function Test(exp) {
switch (exp) {
case 1:
return <One />;
case 2:
return <Two />;
case 3:
return <Three />;
default:
return <None />;
}
}
// this would be if you want to generate a random component
function randomIntFromInterval(min, max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
function App() {
const [renderedComponent, setRenderedComponent] = useState(0);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
// If you want a button for a particular component, you can
// put in that number 1,2,3 instead of the call to randomIntFromInterval
<button onClick={() => setRenderedComponent(randomIntFromInterval(1, 3))}>
Render One Two or Three
</button>
{renderedComponent !== 0 && <Test />}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
但是,这不会阻止按钮再次被单击,并且可能会显示另一个组件。您必须引入逻辑来处理该问题。