通过 .map() 响应本机绑定函数

React Native binding functions over .map()

所以我在结合 .map() 和函数绑定的概念时遇到了一些麻烦。我使用 .map() 的方式与在 angular 中使用 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>
          )
        })
      }
    )
  }
}

因此在Parent Component中,多个MyButtons被正确渲染,每个都根据数组中传递的对象进行渲染。但是,当按下任何按钮时,所有 MyButtons 的所有 pressFunctions 都会触发。

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

我的理解是

functionName = () => {}

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

您应该将 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>
      )
    })
  }
}

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

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

仍然不知道为什么我的它没有引用就不能唯一绑定