pass value from React Native picker component back to VueJS caller

情到浓时终转凉″ 提交于 2021-01-28 19:02:27

问题


I have the following React Native picker component that works -
file name: dynamic-picker.js

import React, { Component } from "react";
import { Container, Content, Picker } from "native-base";

export default class DynamicPicker extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selected: this.props.selected
    }
  }

  onValueChange(value) {
    this.setState({
      selected: value
    });
  }

  itemsList = () => {
    return (this.props.items.map( (item, index) => {
      return (<Picker.Item label={item} key={index} value={item} />)
    }));
  }

  render() {
    return (
      <Container>
        <Content>
            <Picker
              mode="dropdown"
              selectedValue={this.state.selected}
              onValueChange={this.onValueChange.bind(this)}
            >
              { this.itemsList() }
            </Picker>
        </Content>
      </Container>
    );
  }
}

It is being called by a Vue JS file as follows -
file name: distance.vue

<template>
  <dynamic-picker :items="items" :selected="selected" ></dynamic-picker>
</template>

<script>
import DynamicPicker from './dynamic-picker';

export default {
  components: {
    DynamicPicker
  },
  data() {
    return {
      selected: 'yards',
      items: ["yards", "feet", "meters"]
    }
  }
}
</script>

The picker component is being displayed correctly. When the user selects a different option, that change is displayed in the picker component. However, I am stuck on how to get the selected property in the distance.vue file to update when the user selects a different option. That value needs to be captured so it can be passed on to the caller of the distance.vue file and used for a calculation.


回答1:


Figured it out - added a callback to props so the child can call that function to pass data back to the parent when the value is changed.

Here is the updated distance.vue file (parent) -

<template>
  <dynamic-picker :items="items" :selected="selected" :onValueChange="onValueChange" ></dynamic-picker>
</template>

<script>
import DynamicPicker from './dynamic-picker';

export default {
  components: {
    DynamicPicker
  },
  data() {
    return {
      selected: 'yards',
      items: ["yards", "feet", "meters"]
    }
  },
  methods: {
    onValueChange(value) {
      this.selected = value;
    }
  }
}
</script>

Then in dynamic-picker.js (child) the only change necessary was here -

  onValueChange(value) {
    this.setState({
      selected: value
    });
    this.props.onValueChange(value);  // added this line
  }


来源:https://stackoverflow.com/questions/60472136/pass-value-from-react-native-picker-component-back-to-vuejs-caller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!