2017-11-18 104 views
2

使用回調我得到一個子對象的位置並將其添加到數組中。我還想爲該ID添加一個關鍵字,以便稍後可以搜索該陣列。然後我可以將最初創建的對象的鍵與位置數組中的鍵鏈接。回調函數(event,userData)嗎?

我似乎無法得到這兩個工作的回調。有沒有辦法可以讓function(event, callback)都回來?

獎勵積分,如果你知道爲什麼this.props.onLayout在回調中發送e,而this.props.onLayout()則不。我不!

const dataArray = [{key: 0,id: 'A',},{key: 1,id: 'B',},{key: 2,id: 'Z',}] 

// Root Component 
export default class App extends Component { 
    render(){ 
     return (
      <View> 
      {this.getSomeText()} 
      </ 
    getSomeText() { 
     return dataArray.map(d => 
      <SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e)} /> 
     ) 
    } 
    onLayout (e, id) { 
     // add these items to array 
     // e.nativeEvent.Layout{Width,Height,x,y,id} 
     // I can add the e data but the id data never comes through. 
    } 
} 


// Child Component 
class SomeText extends Component { 
    render() { 
     return (
      <Text 
       onLayout={this.props.onLayout} 
       // onLayout as above this returns the event e but 
       // 2. this.props.onLayout() // doesn't return e at all ?? 
       // 3.() => this.props.onLayout // doesn't work either, why? 
       // 4. (e, this.props.key) => this.props.onLayout(this.props.key) 
       // 4 doesnt work either 
       >Some text</Text> 
     ) 
    } 
} 

回答

1

您可以使用:

onLayout (e) { 
    const id = e.target.id; 
} 

看到一些補充,下面您的意見:

<Text 
    onLayout={this.props.onLayout} 
    // onLayout as above this returns the event e but 
    // 2. this.props.onLayout() // Calls the function during every render instead of assigning it. 
    // 3.() => this.props.onLayout // Assigns the anonymous function, but when the event occurs and the anonymous function is called, you aren't calling your onLayout function. 
    // 4. (e, this.props.key) => this.props.onLayout(this.props.key) 
    // this.props.key isn't being passed in by the event handler. Also, you are not passing the event to onLayout. Should be (e) => this.props.onLayout(e, this.props.key) 
    >Some text</Text> 

<SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e, d.id)} /> 

但是,您也可以從事件獲得ID

+0

謝謝,你的回答幫助我把callb的'旅程'非常讚賞。 – denden