回调函数(event,userData)吗?

回调函数(event,userData)吗?

问题描述:

使用回调我得到一个子对象的位置并将其添加到数组中。我还想为该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> 
     ) 
    } 
} 

您可以使用:

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