更改React.js

时间:2018-06-18 13:44:25

标签: reactjs

我需要更改单选按钮的图像。我试图用这种方式做到这一点:当我点击图像时,单选按钮被激活。没关系,但是当我所有的映射图像被选中时,也不是我选择的那个。

这是我的代码:

  handleRadio(e) {
    const { radioBtnSrc } = this.state;
    radioBtnSrc === './img/bullet_off.png' ?
    this.setState({ radioBtnSrc: './img/bullet_on.png' }) : this.setState({ radioBtnSrc: './img/bullet_off.png' });
  }

  renderSurvey() {
    const { radioBtnSrc } = this.state;
    const surveyItem = mockedData.map((item, i) => 

      <h3 key={item.id} className="questions">
        {item.text}
        {item.answers.map((el, j) => 
          <div key={j}>
            <input onClick={(e) =>  this.handleRadio(e)} type="radio" id={i.toString() + j.toString()} name={i} value={j} />

            <label htmlFor={i.toString() + j.toString()}  className="answers">
              <img src={radioBtnSrc} />
            </label>
          </div> )}
      </h3>
      )

    return surveyItem;
  }

显然我在渲染方法中返回它。

我的模拟数据是:

const mockedData = 
[
 {
   "id":782299,
   "id_page":258355,
   "number":1,
   "type":0,
   "date_created":"2011-07-14 22:24:46",
   "date_modified":"2011-12-29 18:04:24",
   "text":"Jednokrotne",
   "desc":"",
   "required":1,
   "answers_count":3,
   "options":{
     "shuffle_answers":false,
     "horizontal_display":false
   },
   "answers":[
     {
       "text":"tak",
       "custom_response_available":false
     },
     {
       "text":"nie",
       "custom_response_available":false
     },
     {
       "text":"inne",
       "custom_response_available":true
     }
   ]
 },
 {
   "id":782300,
   "id_page":258355,
   "number":2,
   "type":6,
   "date_created":"2011-07-14 22:24:58",
   "date_modified":"2011-12-29 18:04:13",
   "text":"Wielokrotne",
   "desc":"",
   "required":1,
   "answers_count":4,
   "options":{
     "min":2,
     "max":2,
     "shuffle_answers":false,
     "horizontal_display":false
   },
   "answers":[
     {
       "text":"tak",
       "custom_response_available":false
     },
     {
       "text":"nie",
       "custom_response_available":false
     },
     {
       "text":"mo\u017ce",
       "custom_response_available":false
     },
     {
       "text":"inne",
       "custom_response_available":true
     }
   ]
 }
];

谢谢你,如果你能提供帮助的话。我想选择一个图像项目来设置单选按钮项目符号。

1 个答案:

答案 0 :(得分:0)

您的数组中的所有项目(radioBtnSrc)看起来都使用相同的状态键,因此更新任何这些项目都会更新列表中的所有项目。

您可以将id添加为状态键的一部分,以便每个项目都有自己独特的状态吗?

您需要将id传递给handleRadio,但之后您可以执行以下操作:

  handleRadio(e, id) {
    const stateKey = `radioBtnSrc-${id}`;
    this.state[stateKey] === './img/bullet_off.png' ?
    this.setState({ [stateKey]: './img/bullet_on.png' }) : this.setState({ [stateKey]: './img/bullet_off.png' });
  }

另一种选择是建立一个对象并将其分配给radioBtnSrc并跟踪每个键的属性。它也可以清理东西,只存储状态而不是图像的完整路径。例如你的州可能看起来像:

  const state = {
    buttons: {
      782299: true,
      782300: false
    }
  } 

只要拥有这些布尔值就可以为您提供足够的信息来构建正确的用户界面。