簡體   English   中英

React JS / React Native:將參數傳遞給render方法中的預定義事件處理程序

[英]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.idTouchableNativeFeedbackthis.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元素(如TouchableNativeFeedbackonPress中將參數傳遞給預定義的事件處理程序onPress={() => this.handleClick(someParam)} )或使用bind

  1. 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

  1. 如果我不想定義一個新的匿名函數(例如,onPress = {(()=> this.handleClick(someParam)}),如何在通用的react元素(如TouchableNativeFeedback的onPress)中將參數傳遞給預定義的事件處理程序)或使用bind

只需創建一個新的組件,如上面的ListItem並更改render方法

renderSingleItem = ({item}) => (
    <ListItem item={item} />
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM