首页 > 解决方案 > 如何在reactjs中更新地图功能中的状态

问题描述

我有 4 个按钮,每个按钮都有名称 id 和选定的布尔标志。

我想要实现的是,单击按钮时,应该更改该特定按钮的布尔按钮标志。为此,我需要在地图函数中为该特定按钮 ID 设置状态。

我的问题是我无法在地图功能中为那个特定的点击按钮设置状态,它的 btnSelected 应该改变

我的目标是创建一个多选取消选择按钮。它为用户提供了一种兴趣选择,并在此基础上反映了 UI 以及我的数组。这是我的代码。

感谢期待。

import React, { Component } from "react";
import { Redirect } from "react-router-dom";

export default class Test extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleChange = this.handleChange.bind(this);
    this.state = {
      value: "",
      numbers: [1, 2, 3, 4, 5],
      posts: [
        {
          id: 1,
          topic: "Animal",
          btnSelected: false
        },
        {
          id: 2,
          topic: "Food",
          btnSelected: false
        },
        {
          id: 3,
          topic: "Planet",
          btnSelected: false
        },
        { id: 4, topic: "Nature", btnSelected: false }
      ],
      allInterest: []
    };
  }

  handleChange(e) {
    //console.log(e.target.value);
    const name = e.target.name;
    const value = e.target.value;
    this.setState({ [name]: value });
  }

  getInterest(id) {
    this.state.posts.map(post => {
      if (id === post.id) {
        //How to setState of post only btnSelected should change
      }
    });
    console.log(this.state.allInterest);
    if (this.state.allInterest.length > 0) {
      console.log("Yes we exits");
    } else {
      console.log(id);
      this.setState(
        {
          allInterest: this.state.allInterest.concat(id)
        },
        function() {
          console.log(this.state);
        }
      );
    }
  }

  render() {
    return (
      <div>
        {this.state.posts.map((posts, index) => (
          <li
            key={"tab" + index}
            class="btn btn-default"
            onClick={() => this.getInterest(posts.id)}
          >
            {posts.topic}
            <Glyphicon
              glyph={posts.btnSelected === true ? "ok-sign" : "remove-circle"}
            />
          </li>
        ))}
      </div>
    );
  }
}

标签: reactjsstatesetstatemap-function

解决方案


以下是你如何做这样的事情:

class App extends Component {
  state = {
    posts: [{
      name: 'cat',
      selected: false,
    }, {
      name: 'dog',
      selected: false
    }]
  }

  handleClick = (e) => {
    const { posts } = this.state;
    const { id } = e.target;
    posts[id].selected = !this.state.posts[id].selected
    this.setState({ posts })
  }

  render() {
    return (
      <div>
        <form>
          {this.state.posts.map((p, i) => {
            return (
              <div>
                <label>{p.name}</label>
                <input type="radio" id={i} key={i} checked={p.selected} onClick={this.handleClick} />
              </div>
            )
          })}
        </form>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

这里的工作示例。


推荐阅读