对象作为React Child无效(找到:带有键{id,name}的对象)

时间:2019-09-11 13:45:58

标签: javascript reactjs react-native radio-button

im试图通过组件的回调在我的react native项目中实现单选按钮

我正在使用反应性单选按钮 SegmentedControls 进入项目

App.js

import files....
import RadioButtons from "../components/RadioButtons";

//Data
const PackingType = [{id:"1", name: "Bag"},{id: "2",name: "Box"}];

export default class App extends Component {
constructor(props) {
    super(props);
    this.state = {
      packTypeSelected: [],
    };
  }
...

  renderAddPackType(selectedOption, selectedIndex) {
    this.setState({ selectedIndex });
    console.log(selectedIndex[0]);
  }

...
render(){
return(
...

 <RadioButtons
            buttonOptions={PackingType}
            callback={this.renderAddPackType.bind(this)}
            selectedOption={"Bag"}
          />

...
)
}

RadioButtons.js

import { SegmentedControls } from "react-native-radio-buttons";
export default class RadioButtons extends Component {
  onSelectedItemsChange = (selectedOption, selectedIndex) => {
    this.props.callback(selectedOption, selectedIndex);
  };

  render() {
    return (
      <View style={{ marginHorizontal: 20, marginVertical: 10 }}>
        <SegmentedControls
          options={this.props.buttonOptions}
          onSelection={(selectedOption, selectedIndex) =>
            this.onSelectedItemsChange(selectedOption, selectedIndex)
          }
          selectedOption={this.props.selectedOption}
        />
      </View>
    );
  }
}

错误:

 Invariant Violation: Invariant Violation: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.
到目前为止,我在开发方面经验不足。 请帮助解决此处的错误

谢谢您的时间

2 个答案:

答案 0 :(得分:2)

因此,我正在阅读react-native-radio-buttons上的文档,只是发现了

  

您还可以指定如何通过extractText属性从选项中提取标签

您的代码中显然缺少哪一个。这是他们希望您做的

  <SegmentedControls
    options={this.props.buttonOptions}
    onSelection={(selectedOption, selectedIndex) =>
      this.onSelectedItemsChange(selectedOption, selectedIndex)
    }
    selectedOption={this.props.selectedOption}
    extractText={ (option) => option.name }
    testOptionEqual={(selectedValue, option) => selectedValue === option.name}
  />

我还没有尝试过,但是我认为它可以工作

答案 1 :(得分:0)

根据该错误,SegmentedControls属性options接受一个ReactNode,并且您分配了一个数组Object

PackingType的类型更改为ReactElement,例如:

// Array Object - throws an error
const PackingType = [{id:"1", name: "Bag"},{id: "2",name: "Box"}];

// ReactNode example
const PackingType = (
  <div>
    {[{ id: "1", name: "Bag" }, { id: "2", name: "Box" }].map(type => (
      <div key={type.id}>{type.name}</div>
    ))}
  </div>
);

// Assigning as props
<RadioButtons
  buttonOptions={PackingType}
  callback={this.renderAddPackType.bind(this)}
  selectedOption={"Bag"}
/>

// Using them inside SegmentedControls
<View>
  <SegmentedControls
    options={this.props.buttonOptions}
  />
</View>

请注意,我没有检查SegmentedControls在options属性中接受的内容,它可能是ReactNode的数组或其他内容,请重新检查它,因为您分配了错误的类型。