我有一个基于switch语句渲染的react组件。 我正在更新交换机所基于的状态,但并非如此
switch (condition) {
case Condition1:
default:
return (
<Condition1Component />
);
case Condition2:
return (
<Condition2Component />
);
case Condition3:
return (
<Condition3Component />
);
}
所有三个组件都以其自己的样式div
包装。
当我从默认状态转到Condition3
时,Condition3
组件被包裹在Condition1 styled div
周围,这很奇怪。
当我将默认状态更改为Condition3
时,一切都会按预期进行。
答案 0 :(得分:1)
看看这是否适合您。
const Container1_DIV = window.styled.div`
color: red;
`;
const Container2_DIV = window.styled.div`
color: blue;
`;
const Container3_DIV = window.styled.div`
color: green;
`;
const Default_DIV = window.styled.div`
color: black;
`;
function App() {
const [myState,setMyState] = React.useState(1);
switch(myState) {
case 1:
return (
<React.Fragment>
<Container1_DIV>I am Container 1</Container1_DIV>
<button onClick={()=>setMyState(1)}>Select 1</button>
<button onClick={()=>setMyState(2)}>Select 2</button>
<button onClick={()=>setMyState(3)}>Select 3</button>
<button onClick={()=>setMyState(4)}>Select 4</button>
</React.Fragment>
);
case 2:
return (
<React.Fragment>
<Container2_DIV>I am Container 2</Container2_DIV>
<button onClick={()=>setMyState(1)}>Select 1</button>
<button onClick={()=>setMyState(2)}>Select 2</button>
<button onClick={()=>setMyState(3)}>Select 3</button>
<button onClick={()=>setMyState(4)}>Select 4</button>
</React.Fragment>
);
case 3:
return (
<React.Fragment>
<Container3_DIV>I am Container 3</Container3_DIV>
<button onClick={()=>setMyState(1)}>Select 1</button>
<button onClick={()=>setMyState(2)}>Select 2</button>
<button onClick={()=>setMyState(3)}>Select 3</button>
<button onClick={()=>setMyState(4)}>Select 4</button>
</React.Fragment>
);
default:
return (
<React.Fragment>
<Default_DIV>I am Default DIV</Default_DIV>
<button onClick={()=>setMyState(1)}>Select 1</button>
<button onClick={()=>setMyState(2)}>Select 2</button>
<button onClick={()=>setMyState(3)}>Select 3</button>
<button onClick={()=>setMyState(4)}>Select 4</button>
</React.Fragment>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<script src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root"/>