【问题标题】:How do you select a particular item/component in React and then cycle through that array onClick?你如何在 React 中选择一个特定的项目/组件,然后在该数组 onClick 中循环?
【发布时间】:2020-07-26 19:55:40
【问题描述】:

我有一个位于绝对位置的返回项目数组。它们相互堆叠,我想知道如何在反应中使用 onClick 方法进行迭代。我有两个按钮,当您单击时,一个应该向前,一个应该向后,但我似乎无法理解。我想以房屋 div 为目标,但似乎无法获得正确的代码来选择该特定项目。我已阅读有关事件处理的文档,但似乎都不起作用。有人能指出我正确的方向吗,因为我是 React 新手?

这是我的代码:

class Members extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: null,
      senators: [],
      represenatives: [],
      bills: []
    }
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value.toUpperCase()
    })
  }

  right = (e) => {


  }

  componentDidMount() {
    const key = `xCaHBd8gI5ZJSOUXWFJGOXZBjJtMbvoIcip0kSmS`
    const urls = [`https://api.propublica.org/congress/v1/116/senate/members.json`,
      `https://api.propublica.org/congress/v1/102/house/members.json`,
      `https://api.propublica.org/congress/v1/statements/latest.json`,
      `https://api.propublica.org/congress/v1/bills/search.json`];

    let requests = urls.map(url => fetch(url, {
      type: "GET",
      dataType: 'json',
      headers: {
        'X-API-Key': key
      }
    }))
    Promise.all(requests)
      .then(res => {
        return Promise.all(res.map(res => res.json()));
      }).then(response => {
        this.setState({
          senators: response[0].results[0].members,
          represenatives: response[1].results[0].members,
          bills: response[2].results
        })
        console.log(this.state.senators)
      }).catch(err => {
        console.log(err)
      })

  }

  render() {

    const { senators, bills, represenatives, userInput } = this.state;

    const inSenate = senators.filter(
      (senator) => senator.state === userInput
    )

    const inHouse = represenatives.filter(
      (represenative) => represenative.state === userInput
    )

    const draft = bills.find(
      (bill) => bill.name === inSenate.last_name)



    return (

      <div className="congress">
        <div className="users">
          <h2>{this.state.userInput}</h2>
          <input className="userInput" onChange={this.handleChange} />
        </div>

        {inSenate.map((senate, i) => {
          return (
            <div key={senate.id} className="senate">
              <h2 className="senateName">Senate</h2>
              <ul className="bio">
                <h2 >{senate.short_title + " " + senate.first_name + " " + senate.last_name}</h2>
                <li>{senate.title}</li>
                <li>State: <strong>{senate.state}</strong></li>
                <li>Party: <strong>{senate.party}</strong></li>
                <li>DOB: <strong>{senate.date_of_birth}</strong></li>
                <li>Next Election: <strong>{senate.next_election}</strong></li>
                <li>Missed Votes: <strong>{senate.missed_votes}</strong></li>
                <li> Votes With Party Percentage: <strong>{senate.votes_with_party_pct + "%"}</strong></li>
                <li>Votes Against Party Percentage: <strong>{senate.votes_against_party_pct + "%"}</strong></li>
              </ul>
            </div>
          )
        })}

        {inHouse.map((rep, i) => {
          return (
            <div className="house"> //this is what I want to cycle through
              <h2 className="numbers" >Your state has {inHouse.length} Represenative(s)</h2>
              <h2 >{rep.short_title + " " + rep.first_name + " " + rep.last_name}</h2>
              <ul className="bio">
                <li  >{rep.title}</li>
                <li  >State: <strong>{rep.state}</strong></li>
                <li  >Party: <strong>{rep.party}</strong></li>
                <li  >DOB: <strong>{rep.date_of_birth}</strong></li>
                <li  >Next Election: <strong>{rep.next_election}</strong></li>
                <li  >Missed Votes: <strong>{rep.missed_votes}</strong></li>
                <li  > Votes With Party Percentage: <strong>{rep.votes_with_party_pct + "%"}</strong></li>
                <li  >Votes Against Party Percentage: <strong>{rep.votes_against_party_pct + "%"}</strong></li>
              </ul>
              <button className="left btn"></button>
              <button onClick={this.right} className="right btn"></button>
            </div>
          )
        })}
      </div>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你已经有变量i这里{inHouse.map((rep, i) =&gt; {

    i 是您在数组inHouse 中的索引。 rep 实际上是 inHouse[i],因此您可以将索引 (i) 作为参数传递给 onClick 函数。

    所以这个:

    right = (e) => {}
    
    ...
    
    
    <button onClick={this.right} className="right btn"></button>
    

    将被替换为:

    right = (index) => {}
    
    ...
    
    <button onClick={() => this.right(i)} className="right btn"></button>
    

    【讨论】:

    • 嗨,您能否对此进行扩展,因为我很难让逻辑正常工作?
    • @Alanaj in right = (index) =&gt; {} 您可以访问要移动的项目的索引,您可以使用 console.log(index) 检查它,所以如果 right() 是为了移动数组中的 item up 你可以在 body 函数中执行,你可以在那里访问this.state,所以你可以简单地做 const inHouse = this.state.inHouse 用 inHouse 做一些事情并用那个值设置状态。
    猜你喜欢
    • 1970-01-01
    • 2014-02-03
    • 2018-03-24
    • 2021-12-14
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2016-01-31
    • 2017-05-01
    相关资源
    最近更新 更多