gpt4 book ai didi

react-native - 如何在 native react 中制作动态复选框

转载 作者:行者123 更新时间:2023-12-04 00:27:23 28 4
gpt4 key购买 nike

我正在制作一个 react native 应用程序,我需要在运行时在其中创建复选框。我的意思是从服务器我将获得 json 对象,该对象将具有复选框的 id 和标签。现在我想知道从服务器获取数据后如何我也制作了复选框,我如何处理复选框,我的意思是有多少个复选框将在那里它不会是静态的,所以我如何声明可以处理复选框的状态变量。另外我如何处理复选框的 onPress 事件.请为我提供一些代码帮助。提前致谢

最佳答案

这个概念将在状态中使用一个数组并使用您从服务响应中获得的数据设置状态数组,复选框在两个平台中都不可用,因此您必须使用 react-native-elements。您可以使用 map 函数来渲染数组中的复选框,并使用 onPress 来相应地更改状态。代码如下。您还必须考虑在状态中维护已检查的值。

import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-elements';

export default class Sample extends Component {

constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, key: 'test1', checked: false },
{ id: 2, key: 'test1', checked: true }
]
};
}

onCheckChanged(id) {
const data = this.state.data;

const index = data.findIndex(x => x.id === id);
data[index].checked = !data[index].checked;
this.setState(data);
}

render() {
return (<View>
{
this.state.data.map((item,key) => <CheckBox title={item.key} key={key} checked={item.checked} onPress={()=>this.onCheckChanged(item.id)}/>)
}
</View>)
}
}

关于react-native - 如何在 native react 中制作动态复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55134845/

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