通过FlatList遍历数组生成的Switch组件怎么实现单独的控制呢?



  • 获得数据后,在FlatList的data中传入了一个数组,并通过这个数组生成了两个开关Switch组件并显示在页面上,那么我应该如何来实现单独的开关状态控制呢?

    代码如下:

    var dataSource = {"code":"N000","data":[{"name":"Switch1","type":"switch","value":0},{"name":"Led1","type":"led","value":1},{"name":"Switch2","type":"switch","value":0}]};
    var jsonData = dataSource['data'];

    class HomeScreen extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    jsonFinalData: []
    };
    }
    static navigationOptions = {
    title: 'Welcome',//设置标题内容
    };
    componentDidMount(){
    var vm = this;
    var temp = [];
    for(var i=0;i<jsonData.length;i++){
    jsonData[i].key=i;
    temp.push(jsonData[i]);
    }
    vm.setState({
    jsonFinalData:temp
    })
    }

    _separator = () => {
        return <View style={{height:2,backgroundColor:'yellow'}}/>;
    }
    
    setSwitchState = (name,value) => {
        alert(name + "  " + value);
        //var newname = name;
        //this.refs[newname].value = !value;
    }
    
    touchevent(item){
        if(item.type=="switch"){
            return (
                <TouchableOpacity
                    key={item.key}
                    onPress={() => alert("Click " + item.name)}>
                    <View style={{backgroundColor: 'white'}} >
                        <Text>switch66666 {item.name} {item.type} {item.value}</Text>
                        <Switch
                            ref={item.name}
                            value={false}
                            onValueChange={(e)=>{this.setSwitchState(item.name,e.value)}}
                        />
                    </View>
                </TouchableOpacity>
            )
        }
        if(item.type=="led"){
            return (
                <TouchableOpacity
                    key={item.key}
                    onPress={() => alert("Click " + item.name)}>
                    <View style={{backgroundColor: 'white'}} >
                        <Text>led66666 {item.name} {item.type} {item.value}</Text>
                    </View>
                </TouchableOpacity>
            )
        }
    }
    
    render() {
        const { navigate } = this.props.navigation;
        return (
            <View>
                <Text>Hello, Navigation!</Text>
                <Button
                    onPress={() => navigate('Chat',{user:'Lucy'})}
                    title="Chat with Lucy"/>
                <Button
                    onPress={() => alert(JSON.stringify(this.state.jsonFinalData))}
                    title="Alert"/>
                <FlatList
                    style={{marginTop:100}}
                    ItemSeparatorComponent={this._separator}
                    data={this.state.jsonFinalData}
                    renderItem={({item}) => this.touchevent(item)}
                />
            </View>
        );
    }
    

    }



  • 按钮想要有自己的状态,组件化


登录后回复