如何在 React 状态下从嵌套的 Array 对象设置 radioGroup 的 defaultValue? [英] How to set defaultValue of a radioGroup from a nested Array object in React state?

查看:50
本文介绍了如何在 React 状态下从嵌套的 Array 对象设置 radioGroup 的 defaultValue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 formRating 的状态数组对象

formRating:Array[22]0:{…}条件:C2.1(a)"费率:不适用"1:{…}condId:"C2.2(b)"率:3"2:{…}3:{…}

我在渲染中还有一些 RadioGroups,让用户可以操作上面的状态对象.

条件 1<Grid item ><RadioGroup name="C2.1(a)" defaultValue={this.getDefaultValue('C2.1(a)')} onChange={this.changeButton("C2.1(a)")} style={{display: 'flex', flexDirection: 'row'}}>

用 defaultValue={this.getDefaultValue("C2.1(a)")} 更改与给定 condId 匹配的元素的比率的 getDefaultValue 方法是什么?

解决方案

使用 .map 定义这些 RadioGroupsdefaultValue 是有意义的() 遍历 formRatings 的列表.然后你可以无缝地传递速率,而不是将硬编码的字符串传递给函数.

尝试类似:

 createRadioGroups = () =>{const { formRating } = this.state;返回 formRating.map(item => {返回 (<div><label>{item.condId}</label><网格项目><广播集团默认值={item.rate}价值={item.rate}名称={item.condId}onChange={() =>this.changeButton(item.condId)}/></网格>

);});};

然后在你的渲染中你可以使用 createRadioGroups()

 render() {返回 (<div><网格项 xs={7} style={{ marginTop: 32 }}>条件 1</网格>{this.createRadioGroups()}

);}

I have this array Object in State called formRating

formRating:Array[22]
0:
 {…}
  condId: "C2.1(a)"
  rate: "N/A"
1:
 {…}
  condId:"C2.2(b)"
  rate:"3"
2:
 {…}
3:
 {…}

I also have a few RadioGroups in the render letting the user manipulate the state object above.

<Grid item xs={7} style={{marginTop:32}}> Condition 1</Grid> <Grid item ><RadioGroup name="C2.1(a)"  defaultValue={this.getDefaultValue('C2.1(a)')} onChange={this.changeButton("C2.1(a)")} style={{display: 'flex', flexDirection: 'row'}}>

What would the getDefaultValue method be to change the rate of an element matching with the given condId with the defaultValue={this.getDefaultValue("C2.1(a)")}?

解决方案

It will make sense to define the defaultValue of these RadioGroups by using a .map() to iterate over the list of formRatings. Then you can pass in the rate seamlessly instead of passing a hard-coded string to a function.

Try something like:

  createRadioGroups = () => {
    const { formRating } = this.state;

    return formRating.map(item => {
      return (
        <div>
          <label>{item.condId}</label>
          <Grid item>
            <RadioGroup
              defaultValue={item.rate}
              value={item.rate}
              name={item.condId}
              onChange={() => this.changeButton(item.condId)}
            />
          </Grid>
        </div>
      );
    });
  };

Then in your render you can use createRadioGroups()

  render() {
    return (
      <div>
        <Grid item xs={7} style={{ marginTop: 32 }}>
          Condition 1
        </Grid>
        {this.createRadioGroups()}
      </div>
    );
  }

这篇关于如何在 React 状态下从嵌套的 Array 对象设置 radioGroup 的 defaultValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆