简体   繁体   English

无法从子组件中获取 map 索引的值以在 React 中作为 function 参数传递

[英]Can't get value of a map index from a child copmonent to pass as function argument in React

This is the first project I'm building in react so i apologise for any errors.这是我在 react 中构建的第一个项目,所以我为任何错误道歉。

I have three components in React.我在 React 中有三个组件。 The method is declared in the top level with two parameters.该方法在顶层声明,带有两个参数。 I pass this method to a child component.我将此方法传递给子组件。 In this component I want to call the method inside a map, using the index of the map as an argument.在这个组件中,我想调用 map 中的方法,使用 map 的索引作为参数。 Here is the code:这是代码:

class App extends Component {
 constructor() {
    super();
    this.state = {
       workExperience: [
          { points: [{id: 1, point: "firstPoint"}, {id: 2, point: "secondPoint"}]
       ]
    }
    this.captureTask = this.captureTask.bind(this);
}

captureTask(e, index){
//clone state, want to access array using map index in child component below and capture value of the input to update this state
clonedState.points[index] = e.target.value
console.log(index) //undefined
}

render(){
   return(
       <ChildComponent captureTask={(e, index) => this.captureTask(e, index)} />
   )
}


class ChildComponent extends Component {
    constructor(props){
        super()
}

render(){
    return(
          <div>
               {this.props.points.map((point, index) => {
                   return <Input key={point.id} handleChange={(e, index) => this.props.captureTask(e, index)} />
                })}
           </div>
     )
}

My issue is in the captureTask method.我的问题出在 captureTask 方法中。 The index value returns undefined when it gets back to the function.索引值返回到 function 时返回 undefined。 However within the Map I'm able to log index value without any issue.但是在 Map 中,我可以毫无问题地记录索引值。 Is there something I should be doing differently in order to be able to use the map index as an argument in a parent method?为了能够使用 map 索引作为父方法中的参数,我应该做些什么不同的事情吗?

Thanks for any help.谢谢你的帮助。

Change the handleChange prop to the following:handleChange更改为以下内容:

handleChange = { (e) => this.props.captureTask(e, index) }

ie Remove the index from the arguments list of the arrow function.即从箭头function的arguments列表中删除index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM