[英]React JS/React Native: passing parameter(s) to a pre-defined event handler in a render method
我在React Native中渲染一些視圖。 從閱讀的內容來看,出於性能原因,我們應該避免定義新函數或在render方法內使用bind。 因此,在這種情況下,我有一個平坦的列表,每個列表項呈現為TouchableNativeFeedback
其調用handleOnPress
在印刷機上。 示例代碼如下。
<FlatList
data={items}
keyExtractor={(item, index) => item.id}
renderItem= {this.renderSingleItem}
extraData={this.state}
/>
和
renderSingleItem = ({item}) => (
<TouchableNativeFeedback onPress={this.handleOnPress}>
<View>
<Text>bla bla bla</Text>
</View>
</TouchableNativeFeedback>
);
在這里我有參數傳遞麻煩handleOnPress
,特別是我需要通過item.id
從TouchableNativeFeedback
到this.handleOnPress
。 在此處的示例https://daveceddia.com/avoid-bind-when-passing-props/中 ,它使用ListItem
,作者說
// handleClick still expects an id, but we don't need to worry
// about that here. Just pass the function itself and ListItem
// will call it with the id.
這真是令人困惑。
我的問題是
1) ListItem
如何在示例https://daveceddia.com/avoid-bind-when-passing-props中將id
傳遞給handleClick
?
<ListItem key={item.id} item={item} onItemClick={handleClick} />
是因為默認情況下它通過了props key
嗎? 看來這是一個瑣碎的問題,但我在本機頁面上找不到ListItem
文檔,也許它已被棄用,如ListView
2)如果我不想定義新的匿名函數(例如, onPress={() => this.handleClick(someParam)}
),如何在通用的react元素(如TouchableNativeFeedback
的onPress
中將參數傳遞給預定義的事件處理程序onPress={() => this.handleClick(someParam)}
)或使用bind
- ListItem如何在示例https://daveceddia.com/avoid-bind-when-passing-props中傳遞ID來處理handleClick?
按照帖子。 我看到了你想要的答案
var ListItem = React.createClass({
render() {
// Don't need a bind here, since it's just calling
// our own click handler
return (
<li onClick={this.handleClick}>
{this.props.item.name}
</li>
);
},
handleClick() {
// Our click handler knows the item's id, so it
// can just pass it along.
this.props.onItemClick(this.props.item.id);
}
});
handleClick
函數的參數沒有id
但它是來自組件props的內容調用id
- 如果我不想定義一個新的匿名函數(例如,onPress = {(()=> this.handleClick(someParam)}),如何在通用的react元素(如TouchableNativeFeedback的onPress)中將參數傳遞給預定義的事件處理程序)或使用bind
只需創建一個新的組件,如上面的ListItem並更改render方法
renderSingleItem = ({item}) => (
<ListItem item={item} />
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.