gpt4 book ai didi

reactjs - react native 。无法从 map 函数内设置引用

转载 作者:行者123 更新时间:2023-12-03 14:14:24 26 4
gpt4 key购买 nike

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

这是我的组件:

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。我的错误在哪里?

最佳答案

尝试将 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 }}
/>)
}
}

关于reactjs - react native 。无法从 map 函数内设置引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com