【问题标题】:Dynamically create buttons in react native在本机反应中动态创建按钮
【发布时间】:2020-06-03 10:51:35
【问题描述】:

我想根据 API 中的数据动态创建一个复选框,然后在我的 render 函数中调用该函数。

任何人都可以建议我,因为我使用了forEach,但数据似乎没有通过,因此我收到一个错误:forEach is undefined

我的sn-p:

sizel=()=> this.state.data.sizes.forEach(function(size){
    <CheckBox
     title={size}
   checked=''
   />
 })

【问题讨论】:

  • 这能回答你的问题吗? React foreach in JSX
  • 你能帮我语法,拜托,我是新手,如果你能帮忙,我会很感激。
  • 没有仍然未定义
  • data.sizes 的值是多少?
  • 我认为您使用 .forEach 编码的问题不会返回您的复选框,只需将其更改为 .map 作为@JosephD。而不是在他的回答中

标签: reactjs react-native react-native-android


【解决方案1】:

检查data.sizes的长度也不应该是未定义的。

添加这个:

const { sizes } = this.state.data;
if( sizes && sizes.length){
 this.state.data.sizes.map(size => <CheckBox title={size} checked=''/> )
}

【讨论】:

    【解决方案2】:

    你需要在调用 forEach 方法之前添加一个验证,就像这样:

       sizel = () => this.state.data && this.state.data.sizes && this.state.data.sizes.forEach(function (size) {
        return (
          <CheckBox
            title={size}
            checked=''
          />
        )
      })
    

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 2020-08-13
      • 2017-05-22
      • 1970-01-01
      • 2017-12-22
      • 2017-05-23
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多