无法理解如何从映射的元素中接收值

时间:2019-04-05 18:30:01

标签: reactjs

我正在获取有关合同区块链中已经存在的虚假用户的信息。我收到的信息只是一个字符串值数组。我将它们设置为状态变量,然后将其全部映射,在组件字段中传递信息并将其带入我们的状态。问题是,我不知道如何从该函数中接收组件的索引。无法理解,如何获取我在其上使用click事件的元素的索引。

我试图只是发送并在函数中建立索引,然后通过单击任何组件,通过控制台查看其功能,并且始终收到未定义的内容。

//这是App.js主文件

handleClick = (index) => {  
console.log(index)
};

render() {

const content =
this.state.candidates.map((voter, index) =>
<Content
              key={index}
              id={index + 1}
              name={voter.charAt(0).toUpperCase() + voter.slice(1)}
              handleClick={this.handleClick}
      / >);

//候选-是字符串元素的数组。

//这是组件

function Content(props) {
const { id, name, account, handleClick,  index } = props;
return (
    <div className="content"   onClick={()=> handleClick(index)}>
        <div>{id}< /div>
        <h4>{name}< /h4 >
        <h5>{account}< /h5>
    </div>
  )
}

我要接收单击的元素的索引。

2 个答案:

答案 0 :(得分:0)

不确定是否已回答。 您有两种选择:

  • this.props.handleClick(id)组件内部调用Content
  • 或在handleClick内的index参数中传递map中的函数,如下所示:
{this.state.candidates.map((voter, index) =>
            <Content
              key={index}
              id={index + 1}
              name={voter.charAt(0).toUpperCase() + voter.slice(1)}
              handleClick={()=>this.handleClick(index)}
            />)
};

答案 1 :(得分:0)

如果要阻止onClick内联函数,可以这样编写:

function Content(props) {
  const { id, name, account, handleClick, index } = props
  return (
    <div
      id={index} // accessible through "e.target.id"
      className="content"
      onClick={handleClick}
    >
      <div>{id}</div>
      <h4>{name}</h4>
      <h5>{account}</h5>
    </div>
  )
}
handleClick = e => {  
  console.log(e.target.id) // gives you the index
}

render() {
  const content = this.state.candidates.map((voter, index) => (
    <Content
      key={index}
      index={index} // Don't forget to pass this down as props
      id={index + 1}
      name={voter.charAt(0).toUpperCase() + voter.slice(1)}
      handleClick={this.handleClick} // no inline, just pass reference
    />
  )

  return (
    // ...
    { content } 
    // ...
  )
}