[ React-Native: ScrollView, refs, and custom components ]
I'm trying to understand how to do 2 things in React-Native.
Question 1: I have a component and another custom component that I need to scroll inside of a ScrollView.
The problem is that I'm too new to react-native to understand how from my 'child' component I can get access to the scrollview. Note: if I don't use the custom component and put everything into the MainView component, the code works fine.
Here's the basics of the code:
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')}
/>
)
}
}
Question 2: how can I have my 'child' (MyCustomComponent) component call a method that is implemented on the parent component (MainView). The reason for this is that I have a bunch of slightly different 'MyCustomComponents' and I don't want to implement the same boilerplate code to scroll in all of them.
Answer 1
For question 2: The approach I am using is to pass the method into props of your child component and call it when needed.
Answer 2
Thanks to @yang-lei for pointing me in one direction. Here's what I ended up doing:
For 'child' component in the 'parent' component, passed in a function:
<MyCustomComponent onFocusFunction={this.gainFocus.bind(this)} onDismissFunction={this.dismissFocus.bind(this)} />
In 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>
)
}
In 'parent' component:
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);
}