简体   繁体   中英

Update parent component in react native from component attached to scrollview

I have scroll view in my HomeScreen with my measures that is array of Measure component.

<ScrollView>{measures}</ScrollView>

My Measure component looks like this:

class Measure extends Component {
  render() {
    return (
      <View key={this.props.keyval}>
        <TouchableOpacity onPress={deleteItem(this.props.val.measure_id)}>
          <Text style={styles.measure}>
            ID: {this.props.val.measure_id}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
  deleteItem(id) {
    // delete item
    );
  }
}

My question is, how to notify parent component HomeScreen that Measure was deleted to reload scroll view items? Or Maybe you have better idea how to:

  1. display measures
  2. delete one in onPress item
  3. reload items in scroll view

Thans for any advices

In your case it should be something like this:

class HomeScreen extends Component {
  state = {
    measures: []
  };

  handleDelete = (id) => {
    // item was deleted
  }

  render() {
    const { measures } = this.state;

    const measuresList = measures.map(measure => (
      <Measure 
         key={measure.measure_id}
         onDelete={this.handleDelete}
         val={measure}
      />
    ));

    return (
     <ScrollView>{measuresList}</ScrollView>
    );
  }
}


class Measure extends Component {
  render() {
    return (
      <View key={this.props.keyval}>
        <TouchableOpacity onPress={deleteItem(this.props.val.measure_id)}>
          <Text style={styles.measure}>
            ID: {this.props.val.measure_id}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
  deleteItem(id) {
    const { onDelete } = this.props;
    // delete item
    onDelete(id); //will call parent method.
  }
}

I recommend using FlatList as it render only those items which are visible. Much better in terms of performance, especially in big lists taken from API.

Example:

<FlatList
  data={measures}
  keyExtractor={item => item.id}
  renderItem={({ item }) => <Measure 
    id={item.id} 
    anyOtherNeededPropsKey={anyOtherNeededPropsValue}
  />}
/>

将附加属性 onDelete 传递给 Measure 并在 deleteItem 方法中调用它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM