如何在reactjs

时间:2018-04-29 08:22:39

标签: reactjs state setstate map-function

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

我想要实现的是,点击按钮,应该更改该特定按钮的布尔按钮标志。为此,我需要在map函数中为该特定按钮Id设置set。

我的问题是我无法在地图函数中为该特定点击按钮设置setState,其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>
    );
  }
}

2 个答案:

答案 0 :(得分:3)

以下是您执行此操作的方式:

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'));

工作示例here

答案 1 :(得分:0)

您可以通过将地图中的索引传递到每个按钮的handleClick函数中来执行此操作,然后该函数将返回可以由onClick事件触发的另一个函数。

与Colin Ricardo的答案相反,此方法避免将id道具添加到仅用于确定handleClick中的索引的map函数的每个子项上。我在这里修改了Colin的示例以显示比较。请注意,不再需要使用event参数。

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

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

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

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

工作示例here