反应原生。无法在地图功能中设置ref

时间:2017-02-18 21:01:45

标签: reactjs react-native

我正在尝试为使用ref函数创建的每个组件创建map

这是我的组成部分:

class Foo extends Component {

constructor(props) {
   super(props)
}

render() {
  return (
   <ScrollView>
     {this.state.barList.map(createSlides)}
   </ScrollView>
)
}

const createSlides = (uri, i) => (<CarouselItem
                        onPress={() => {}}
                        imgUrl={uri}
                        itemWidth={carouselItemWidth}
                        padding={carouselItemPadding}
                        key={i}
                        ref={(slide) => { this['slide_' + i] = slide}}
                      />);

如您所见,我正在设置ref,但稍后在尝试访问ref时,它会给我undefined。我的错误在哪里?

1 个答案:

答案 0 :(得分:3)

尝试将createSlides方法放入Component

class Foo extends Component {

  constructor(props) {
    super(props)
    // make sure this method gets the right scope, no matter how it's called
    this.createSlides = this.createSlides.bind(this)
  }

  render() {
    return (
      <ScrollView>
        {this.state.barList.map(this.createSlides)}
      </ScrollView>
    )
  }

  createSlides(uri, i) {
    return (<CarouselItem
      onPress={() => { }}
      imgUrl={uri}
      itemWidth={carouselItemWidth}
      padding={carouselItemPadding}
      key={i}
      ref={(slide) => { this['slide_' + i] = slide }}
    />)
  }
}