首页 > 解决方案 > 滚动到 react-native scrollview 动态子项

问题描述

我创建了一个呈现动态表单元素的滚动视图。我可以为滚动视图的每个动态子项创建“ref”。但我面临的问题是我想滚动到表单中存在验证错误的确切子项。但是我找不到每个孩子相对于滚动视图的实际位置,因此我可以滚动到该元素。

我曾尝试将 onLayout 方法添加到子组件,但它在加载时只返回一次位置,然后该值保持不变,即使在滚动之后也是如此。

我的滚动视图

<ScrollView style={{marginBottom: 55}} ref={(ref) => { this.formScrollList = ref; }}>
  {this.state.formElements.map((element, i) => {
    return (
      <TextboxInput quesNo={element.key + 1} required={element.required} error={this.state.errors[element.question_id]} quesType={element.type} quesId={element.question_id} placeholder={element.placeholder} onChangeHandler={this.onChangeHandler} label={element.label} defaultValue={this.state.answers[element.question_id]} showRequired={this.showRequired} index={element.index}/>
    )
  })}
</ScrollView>

我的 TextboxInput 孩子

const TextboxInput = (props) => (
    <View style={styles.inputContainer} ref={setRef}>
        <Text style={styles.text}>{props.label || "Textbox"}{props.showRequired(props.required)}</Text>
        <TextInput style={[styles.textInput, props.error === "empty" ? {borderWidth: 1, borderColor: "red"} : null]} {...props} onChangeText={props.onChangeHandler.bind(this, props.quesId, props.quesType, props.index)} placeholder={props.placeholder} underlineColorAndroid="transparent" defaultValue={props.defaultValue}/>
    </View>
)

我想滚动到表单中存在验证错误的确切子项。

标签: react-nativescrollviewpositioningref

解决方案


使用 scrollview 组件的 scrollTo 方法。


推荐阅读