使用模式获取用户复选框输入并将数据返回到父组件

时间:2019-05-09 07:02:28

标签: react-native

我有一个Newevent类组件,它需要几个用户输入。其中一个是一组称为访问列表的用户ID,其余的是文本输入。这是我正在考虑的代码:

export default class NewEvent extends React.Component {

    state = {
        name: '', 
        access_list: [],
        modalVisible: false
        };
triggerModal() {
    this.setState(prevState => {
      return {
        display: true
      }
    });
  }

render() {
        return (
        <View style={styles.container}>
            <TextInput
                style={styles.input}
                placeholder='Name'
                autoCapitalize="none"
                placeholderTextColor='white'
                onChangeText={val => this.onChangeText('name', val)}
            />


            <Button 
               onPress = { () => this.triggerModal() }
               title = "Open Modal"
               color = "orange">
            </Button>
            <DisplayModal
              visible={this.state.modalVisible}

            />

            <Button
            title='Save'
            onPress={this.save}
            />
        </View>
        )
    }
}

DisplayModal.js中,它是一个功能组件,用于显示一系列复选框,允许用户检查要包括在访问列表中的用户:

import React from 'react'
import { Modal, View, Image, Text, StyleSheet } from 'react-native';
import { CheckBox } from 'react-native-elements'

const DisplayModal = (props) => (
  <Modal visible={ props.display } animationType = "slide" 
         onRequestClose={ () => console.log('closed') }>>
    <View>
      <CheckBox
        title='Click Here1'
        checked={this.state.checked}
      />
      <CheckBox
        title='Click Here2'
        checked={this.state.checked}
      />
    </View>
  </Modal>
)

关于构造DisplayModal.js以返回用户选择的任何建议吗?

1 个答案:

答案 0 :(得分:1)

我不确定这个问题,但我认为您要为此从DisplayModalNewsevent发送状态,至少有两种方法:

1-使用redux,它有点(或太复杂)。您可以阅读the documentation

2-使用props,该函数将数据从子组件返回到父组件。 例如:

export class DisplayModal extends Component {
  state = {
    item1: false,
    item2: false
  };
  _updateState = item => {
    this.setState({ item: !this.state[item] });
    // use the getState props to get child state
    return this.props.getState(this.state);
  };
  render() {
    return (
      <Modal
        visible={props.display}
        animationType="slide"
        onRequestClose={() => console.log("closed")}
      >
        >
        <View>
          <CheckBox
            title="Click Here1"
            checked={this.state.checked}
            onPress={() => this._updateState("item1")}
          />
          <CheckBox
            title="Click Here2"
            checked={this.state.checked}
            onPress={() => this._updateState("item2")}
          />
        </View>
      </Modal>
    );
  }
}

并使用getState道具来获取用户的选择:

<DisplayModal getState={(items)=> this.setState({userSelections:items}) />

DisplayModal上执行每个操作后(即在按下复选框时),_updateStateprops中将该函数调用该函数,在您的示例中,该函数从子级获取数据并更新父级状态