在回调中都返回函数(event,userData)?

时间:2017-11-18 00:58:32

标签: javascript reactjs react-native

使用回调我获取子对象的位置并将其添加到数组中。我还想为该id添加一个键,以便稍后我可以搜索数组。然后我可以使用位置数组中的键链接最初创建的对象的键。

我似乎无法获得两者的回调。有没有办法可以将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 个答案:

答案 0 :(得分:1)

您可以使用:

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

但是,您也可以从事件中获取ID:

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>