首页 > 解决方案 > 在 react-native 中动态更改函数 onPress 处理程序

问题描述

有没有办法动态更改onPress函数处理程序<FlatList>?我有三个onPress需要通过数组传递的函数。如何更新<TouchableOpacity>动态传递给的函数或函数名称(请参阅下面的代码)?

我的输入数组:

const menu = [
{
  "id": 1,
  "route": "this.onBottonPressedHome.bind(this)",
  "info": "1"
},
{
    "id": 2,
    "route": "this.onBottonPressedSettings.bind(this)",
    "info":"2"
},
{
    "id": 3,
    "route": this.onBottonPressedHistory.bind(this)",
    "info": "3"
}

]

我的平面列表:

<FlatList
horizontal={true}
data={menu}
keyExtractor={item => item.id.toString()}
showsHorizontalScrollIndicator={false}
renderItem={({ item, index }) => (
    <TouchableOpacity
    onPress={item.route}
    >
        <Card>
            <CardItem style={{ backgroundColor: '#37BBE1'}}>
                <Body>
                    <View style={{ paddingTop: 10, width: 135 }}>
                        <Text style={{ fontSize: 12, textAlign:'justify', color: '#fff' }}>
                            {item.info}
                        </Text>
                    </View>
                </Body>
            </CardItem>
        </Card>
    </TouchableOpacity>

当我这样做时,我收到一个错误,指出bind未在数组中定义。我该如何解决这个问题?

更新:

我已经使用三元运算符实现了这一点,好吗?这会在性能问题上产生任何问题吗?

标签: javascriptreact-native

解决方案


如果我理解正确,您的menu数组由具有字符串值字段的对象项组成(即没有“真正的”函数绑定)。

假设这是您必须解决的约束,您可能会考虑使用不同的方法来解决此问题,而不是onPress在渲染时动态传递处理程序,而是在事件期间动态解析处理程序,如下所示:

render() {

  /* This handler dynamically selects the action to call, based on the "item"
  that the user has pressed */
  const onPressItemHandler = (item) => {
    switch(item.id) {
      case 1: {
        this.onBottonPressedHome();
        break;
      }
      case 2: {
        this.onBottonPressedSettings();
        break;
      }
      case 3: {
        this.onBottonPressedHistory();
        break;
      }
    }
  }

  return <FlatList
  horizontal={true}
  data={menu}
  keyExtractor={item => item.id.toString()}
  showsHorizontalScrollIndicator={false}
  renderItem={({ item, index }) => (
      <TouchableOpacity
      onPress={ () => onPressItemHandler(item) }>
          <Card>
              <CardItem style={{ backgroundColor: '#37BBE1'}}>
                  <Body>
                      <View style={{ paddingTop: 10, width: 135 }}>
                          <Text style={{ 
                             fontSize: 12, 
                             textAlign:'justify', 
                             color: '#fff' }}>
                              {item.info}
                          </Text>
                      </View>
                  </Body>
              </CardItem>
          </Card>
      </TouchableOpacity>)} />      
}

推荐阅读