在类组件中选择React Native下拉选择器的项不起作用

h6my8fg2  于 2023-10-22  发布在  React
关注(0)|答案(2)|浏览(142)

我正在使用一个React Native Class组件,我想集成一个下拉选择器,因此我使用了react-native-dropdown-picker。下拉选择器显示正常,但从菜单中选择一个值会使我的应用程序崩溃。

import DropDownPicker from 'react-native-dropdown-picker';

class MyClass extends Component {
   constructor(props) {
      super(props);
      this.state = {
         open: false,
         value: ['val1', 'val2', 'val3'],
         items: [
            {label: 'Value1, value: 'val1'},
            {label: 'Value1_1, value: 'val1_1', parent: 'val1'},
            {label: 'Value1_2, value: 'val1_2', parent: 'val1'},
            {label: 'Valu21, value: 'val2'},
            {label: 'Value2_1, value: 'val2_1', parent: 'val2'},
            {label: 'Value2_2, value: 'val2_2', parent: 'val2'},
            {label: 'Value3, value: 'val3'},
            {label: 'Value3_1, value: 'val3_1', parent: 'val3'},
            {label: 'Value3_2, value: 'val3_2', parent: 'val3'}],
      }
      ...
      handleValueChanged = (newVal) => {
         setState((state => ({ value: newVal }));
      }
      render() {
         return(
            ...
            <DropDownPicker
            open={this.state.open}
            value={this.state.value}
            items={this.state.items}
            setOpen={(open) => this.setState({ open })}
            setValue={this.handleValueChanged}
            setItems={(items) => this.setState({ items})}
            mode="BADGE"
            />
            ...
         )
      }
   }
}

我收到一个TypeError: Type error,当我想在我的handleValueChanged函数中使用console.log(newVal)将新选择的值打印到控制台时,整个函数都会被打印出来(当然,这也是类型错误,因为我想更新一个数组)。

function (state) {
   if (multiple) {
   ...
   }
}

此外,原始的documentation类组件似乎不工作。所以主要的问题是:如何使用setValue正确设置我的value

yshpjwxd

yshpjwxd1#

我认为value必须是单个值,而不是数组。你能试试这个吗?

constructor(props) {
      super(props);
      this.state = {
         open: false,
         value: 'val1', // single value
         items: [
            // ...
         ],
      }
   }

   handleValueChanged = (newVal) => {
      this.setState({ value: newVal }); // Corrected
   }
xdnvmnnf

xdnvmnnf2#

我不得不改变这个

handleValueChanged = (newVal) => {
   setState((state => ({ value: newVal }));
}

handleValueChanged = (newVal) => {
         setState((state => ({ value: newVal(state.value)}));
}

相关问题