我有一个由 React、Typescript 和样式组件构建的应用程序(打字稿和样式组件的初学者)。我想创建一个简单的点击事件,在两个子组件中的哪一个在父组件内可见之间切换。你能帮我修复我的代码或建议另一种方法吗?
这是我在//评论中无法解决的部分的代码:
let flipSwitch: boolean = false;
export const myCard: React.FC<myProps> = (props) => {
return (
<Parent onClick={e => {
if (!flipSwitch) {
// dontn't know how to write this part:
//e.get Child1 element.style.display = 'none';
//e.get Child2 element.style.display = 'none';
flipSwitch = true;
} else {
//e.get Child2 element.style.display = 'none';
//e.get Child1 element.style.display = 'block';
flipSwitch = false;
}
}
}>
<Child1>
<GrandChild>{props.whatever}</GrandChild>
<GrandChild2>{props.whatever}</GrandChild2>
</Child1>
<Child2>
<GrandChild3>{props.whatever}</GrandChild3>
<GrandChild4>{props.whatever}</GrandChild4>
</Child2>
</Parent>
)
}
您可以在组件本身上使用状态和条件状态:
import React, { useState } from 'react';
export const myCard: React.FC<myProps> = (props) => {
const [flipSwitch, setFlipSwitch] = useState(false)
return (
<Parent onClick={e => setFlipSwitch(!flipSwitch)}>
{flipSwitch &&
<Child1>
<GrandChild>{props.whatever}</GrandChild>
<GrandChild2>{props.whatever}</GrandChild2>
</Child1>
}
{!flipSwitch &&
<Child2>
<GrandChild3>{props.whatever}</GrandChild3>
<GrandChild4>{props.whatever}</GrandChild4>
</Child2>
}
</Parent>
)
}
我真的不知道应该在您的代码中显示哪一个,但请随意玩玩 ^^
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句