gpt4 book ai didi

reactjs - 如何设置最后一个 Accordion 始终打开?

转载 作者:行者123 更新时间:2023-12-03 14:30:43 24 4
gpt4 key购买 nike

目前,所有 Accordion 都在打印机上切换。但我想将“个人信息” Accordion 设置为始终打开。其余的其他 Accordion 可以切换它们的行为。我尝试使用钩子(Hook)切换功能,但不知道如何保持单个 Accordion 始终打开?

export default function Accordion({
title,
children,
}) {
const [state, setState] = useState(false);

function toggle() {
return (state ? setState(false) : setState(true))
}
const childComponent = (
<View >
{children}
</View>
)
return (
<View>
<TouchableOpacity
onPress={toggle}>
<View>
<Text >
{title}
</Text>
</View>
</TouchableOpacity>
{state && childComponent}
</View>
)
}



class App extends React.Component {

render() {
return (
<ScrollView>
<Accordion
title='Contacts'>
<Text >Contact screen will be here</Text>
</Accordion>
<Accordion
title='Document>
<Text >Document screen will be here</Text>
</Accordion>
<Accordion
title='Personal info'>
<Text >Personal info screen will be here</Text>
</Accordion>
</ScrollView>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />

最佳答案

您可以做的是接收一个 Prop ,该 Prop 将定义它是否应该打开并且不使用切换

export default function Accordion({
title,
children,
alwaysOpened,
}) {
const [state, setState] = useState(false);

useEffect(() => {
if(alwaysOpened)
setState(!!alwaysOpened)
}, [alwaysOpened])

function toggle() {
if(!alwaysOpened)
return (state ? setState(false) : setState(true))
}

const childComponent = (
<View >
{children}
</View>
)
return (
<View>
<TouchableOpacity
onPress={toggle}>
<View>
<Text >
{title}
</Text>
</View>
</TouchableOpacity>
{state && childComponent}
</View>
)
}

然后将属性alwaysOpened传递给您想要始终打开的Accordion

    <Accordion
alwaysOpened
title='Personal info'>
<Text >Personal info screen will be here</Text>
</Accordion>

关于reactjs - 如何设置最后一个 Accordion 始终打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57462066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com