React-Native:ScrollView,refs和自定义组件

React-Native: ScrollView, refs, and custom components

本文关键字:自定义 组件 refs ScrollView React-Native      更新时间:2023-09-26

我试图了解如何在 React-Native 中做 2 件事。

问题 1:我有一个组件和另一个自定义组件,我需要在 ScrollView 中滚动。

问题是我太新了,无法理解如何从我的"子"组件访问滚动视图。注意:如果我不使用自定义组件并将所有内容放入 MainView 组件中,则代码工作正常。

以下是代码的基础知识:

class MainView extends React.Component{
  render() {
    return (
    <ScrollView ref='scrollView'>
      <MyCustomComponent />
    </ScrollView>
    )
  }
}

class MyCustomComponent extends React.Component{
  inputFocused(refName) {
    setTimeout(() => {
      let scrollResponder = this.refs.scrollView.getScrollResponder();
      scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
        React.findNodeHandle(this.refs[refName]),
        110, //additionalOffset
        true
      );
    }, 50);
  }
  render() {
    return (
    <TextInput ref='fieldtitle'
      onFocus={this.inputFocused.bind(this, 'fieldtitle')}
      />
    )
  }
}

问题 2:如何让我的"子"(MyCustomComponent)组件调用在父组件 (MainView) 上实现的方法。这样做的原因是我有一堆略有不同的"MyCustomComponents",我不想实现相同的样板代码来滚动所有这些组件。

对于问题 2:我正在使用的方法是将该方法传递到子组件的 props 中,并在需要时调用它。

感谢@yang-lei为我指出一个方向。这是我最终做的事情:

对于"父"组件

中的"子"组件,在函数中传递:

<MyCustomComponent onFocusFunction={this.gainFocus.bind(this)} onDismissFunction={this.dismissFocus.bind(this)} />

在 MyCustomComponent 中:

inputFocused(refName) {
  this.props.onFocusFunction(this, refName)
}
dismissFocus(refName) {
  this.props.onDismissFunction(this, refName)
}
render() {
  var field = this.props.fieldInfo;
  placeholder = field.placeholder ? field.placeholder : ""
  return (
    <View style={styles.inputRow}>
    <Text style={styles.textField}>{this.props.fieldInfo.title}</Text>
    <TextInput ref={field.title}
      style={styles.textInput}
      onChange={this.handleChange.bind(this)}
      keyboardType='email-address'
      placeholder={placeholder}
      onFocus={this.inputFocused.bind(this, field.title)}
      onBlur={this.dismissFocus.bind(this, field.title)}
      />
    </View>
  )
}

在"父"组件中:

gainFocus(view, refName) {
  setTimeout(() => {
    let scrollResponder = this.refs.scrollView.getScrollResponder();
    scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
      React.findNodeHandle(view.refs[refName]),
      110, //additionalOffset
      true
    );
  }, 0);
}
dismissFocus(view, refName) {
  setTimeout(() => {
    let scrollResponder = this.refs.scrollView.getScrollResponder();
    scrollResponder.scrollResponderScrollTo(
    )
  }, 0);
}