将检查的复选框添加到阵列中,然后删除未检查的复选框 - 反应本机



我需要做的是 - 在数组中添加/添加/删除每个复选框的名称(由用户检查/未检查)并发送到服务器。我陷入以下代码中。任何帮助都将受到赞赏。谢谢

class App extends Component<Props> {
  render() {
    return (
      <View style={{ padding: 15 }}>
        {
            response.map(
              item => {
                return (
                  <CheckBoxItem label={item.name} />
                );
              }
            )
        }
       </View>
    );
  }
}

checkboxitem.js

class CheckBoxItem extends Component<Props> {
  state = {
    check: false,
    problemTypeArray: [],
  }
  changeArray = (label) => {
      let array = [...this.state.problemTypeArray, label];
      let index = array.indexOf(label);
      console.log('array', array);//returns array with length 1 all the time
  }
  render() {
    return (
      <View>
        <CheckBox value={this.state.check} onValueChange={(checkBoolean) => { this.setState({ check: checkBoolean }); this.changeArray(this.props.label); }} />
        <MyText>{this.props.label}</MyText>
      </View>
    );
  }
}
export default CheckBoxItem;

真正的技巧是维护父组件中所选项目的列表。每个CheckBoxItem都可以控制其自己的状态,但是您需要在每次检查/未选中时将值传递回父组件。

由于您尚未显示CheckBox组件的来源,因此我将使用react-native-elements CheckBox向您展示如何进行操作。然后可以将原理应用于您自己的CheckBox

这是App.js

import CheckBoxItem from './CheckBoxItem'
export default class App extends React.Component {
  // set some initial values in state
  state = {
    response: [
      {
        name:'first'
      },
            {
        name:'second'
      },
            {
        name:'third'
      },
      {
        name:'fourth'
      },
            {
        name:'fifth'
      },
            {
        name:'sixth'
      },
    ],
    selectedBoxes: [] // this array will hold the names of the items that were selected
  }
  onUpdate = (name) => {
    this.setState(previous => {
      let selectedBoxes = previous.selectedBoxes;
      let index = selectedBoxes.indexOf(name) // check to see if the name is already stored in the array
      if (index === -1) {
        selectedBoxes.push(name) // if it isn't stored add it to the array
      } else {
        selectedBoxes.splice(index, 1) // if it is stored then remove it from the array
      }
      return { selectedBoxes }; // save the new selectedBoxes value in state
    }, () => console.log(this.state.selectedBoxes)); // check that it has been saved correctly by using the callback function of state
  }
  render() {
    const { response } = this.state;
    return (
      <View style={styles.container}>
        {
          response.map(item => <CheckBoxItem label={item.name} onUpdate={this.onUpdate.bind(this,item.name)}/>)
        }
      </View>
    );
  }
}

这是CheckBoxItem

import { CheckBox } from 'react-native-elements'
class CheckBoxItem extends Component<Props> {
  state = {
    check: false, // by default lets start unchecked
  }
  onValueChange = () => {
    // toggle the state of the checkbox
    this.setState(previous => {
      return  { check: !previous.check }
    }, () => this.props.onUpdate()); 
    // once the state has been updated call the onUpdate function
    // which will update the selectedBoxes array in the parent componetn
  } 
  render() {
    return (
      <View>
        <CheckBox 
          title={this.props.label}
          checked={this.state.check} 
          onPress={this.onValueChange} 
        />
      </View>
    );
  }
}
export default CheckBoxItem;

说明

创建CheckBoxItem时,将两件事传递给它。一个是标签,第二个是onUpdate函数。onUpdate功能将CheckBoxItem链接回父组件,以便可以操纵父中的状态。

在应用此更新之前,onUpdate功能采用状态的先前值,并且看起来查看复选框的名称是否存在于selectedBoxes数组中。如果它存在于selectedBoxes数组中,则将其删除,否则将添加。

现在存在一个数组中的父组件中,您可以访问其中包含所有已选择的项目。

小吃

想尝试我的代码吗?好吧,我创建了一种零食,可以显示它可以正常工作https://snack.expo.io/@andypandy/checkboxes

设置状态

您可能已经注意到我正在用setState做一些不寻常的事情。我确保通过使用状态的先前值,然后将我的更新应用于此,可以正确调用setState。我还使用这样一个事实,即setState在更新状态后会进行回调以执行操作。如果您想阅读更多信息,这里有一些关于setState的精彩文章。

  • https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
  • https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
  • https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6

最新更新