2016-04-27 85 views
0

我有一個使用onLayout屬性的組件。不過,我還想從父組件接收prop,並執行給定的方法以及內部方法。聯合方法調用onLayout

在我的組件我有

onLayout = event => { 
    const { width } = event.nativeEvent.layout; 
    this.setState({ width: width }); 
} 

,並在渲染方法我有

const { onLayout } = this.props; 
return (
    <View onLayout={this.onLayout}> 
    ... 
    </View> 
) 

我怎樣才能結合onLayout道具與內部this.onLayout?我可以創建一個新的方法,但我該如何處理event參數,保持ES6語法?函數原型的

+1

我想添加es2015標籤。這似乎與這個問題真的很相關。 – evolutionxbox

+1

同時刪除三個後退標記以更好地格式化代碼。 – evolutionxbox

回答

1

我認爲,創造新方法將兩個子方法的好辦法:

onLayout = event => { 
    this.props.onLayout(event); 
    this.updateWidth(event); 
} 

updateWidth = event => { 
    const { width } = event.nativeEvent.layout; 
    this.setState({ width: width }); 
} 

並在渲染中:

return (
    <View onLayout={this.onLayout.bind(this)}> 
    ... 
    </View> 
) 
+0

整潔的解決方案:) – Adamski

1

使用bind方法給你的函數綁定到當前環境:

<View onLayout={this.onLayout.bind(this)}>

+0

我不明白這將如何執行這兩種方法? – Adamski

1

@尤里的回答是一個很好的線索。

我通過bind通過onLayout作爲參數:

onLayoutInternal = (onLayout, event) => { 
    const { width } = event.nativeEvent.layout; 
    this.setState({ width: width }); 
    onLayout(event); 
} 

使用綁定像這樣:

render() { 
    const { onLayout } = this.props; 
    return (
    <View onLayout={this.onLayoutInternal.bind(this, onLayout)}> 
) 
}