在.map()上反应Native绑定函数

问题描述 投票:0回答:2

所以我在组合.map()和函数绑定的概念时遇到了一些麻烦。我使用.map()的方式与在角度中使用ngFor相同,在页面上为用户帐户中的每个项目放置一个自定义按钮组件。

这是一些示例代码:

class MyButton extends Component {
  constructor(props) {
    super();
    this.state = {
      progress: 0
    }
  }

  render() {
    return(
      <TouchableWithoutFeedback onPress={this.pressFunction}>
        (...more code inside)
      </TouchableWithoutFeedback>
    )
  }

  pressFunction = () => {
    (animate progress from 0 to 1 for some animation)
  }
}

/////////////////////////////////////////////////////////////////

class Parent extends Component {
  render() {
    return(
      {
        this.props.data.array.map(obj => {
          return(
            <View style={someStyle}>
              <MyButton data={obj} />
            </View>
          )
        })
      }
    )
  }
}

因此,在父组件中,正确呈现多个MyButton,每个MyButton根据数组中传递的对象。但是,当按下任何按钮时,所有MyButton的所有pressFunction都会激活。

我的问题是,我想如何确保每个MyButton的每个pressFunction只绑定到MyButton的特定实例?我在这里的范围有问题。

我的理解是

functionName = () => {}

应该正确地将函数绑定到实例,但我也尝试过较旧的方法,但结果相同。

reactjs react-native react-native-android react-native-ios
2个回答
1
投票

我通过在映射到MyButton的每个对象上创建动态引用来解决这个问题,使用数组中每个obj的唯一属性:

this.props.data.array.map(obj => {
  return(
    <View style={someStyle}>
      <MyButton ref={obj.name} data={obj} />
    </View>
  )
})

仍然不知道为什么我没有ref没有绑定


0
投票

你应该传递onPress作为道具。以下是更新的代码

class MyButton extends Component {
  constructor(props) {
    super();
    this.state = {
      progress: 0
    }
  }

  render() {
    return(
      <TouchableWithoutFeedback onPress={this.props.onPress}>
        (...more code inside)
      </TouchableWithoutFeedback>
    )
  }
}

/////////////////////////////////////////////////////////////////

class Parent extends Component {
  pressFunction = () => {
    (animate progress from 0 to 1 for some animation)
  }
  render() {
    return this.props.data.array.map(obj => {
      return(
        <View style={someStyle}>
          <MyButton 
            data={obj} 
            onPress={this.pressFunction}
          />
        </View>
      )
    })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.