[英]How to use ref in React Navigation header
我在 React 导航的 navigationOptions 中添加了一个带有按钮(即搜索图标)的搜索栏。 现在我想用navigate
功能发送输入的文本。 我不知道如何通过 TextInput 的引用来获取其原生文本。 以下是我到目前为止所做的代码。
static navigationOptions = ({ navigation }) => (
headerStyle: {
...
},
headerTitle: (
<View style={{ width: '100%', height: 75, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 50, backgroundColor: 'white' }}>
<TextInput style={{ width: '85%', padding: 15 }}
onSubmitEditing={
(e) => (e.nativeEvent.text.length > 2) && navigation.navigate('Brands', {text: e.nativeEvent.text})
} />
<TouchableOpacity style={{ width: '15%', padding: 15 }}
onPress={() => navigation.navigate('Brands'/*, {text: HERE I WANT TO GET TEXT FROM REFERENCE}*/)}>
<Icon type='FontAwesome' name='search'
style={{ color: 'red', 20, textAlign: 'center' }} />
</TouchableOpacity>
</View>
)
)};
但是由于navigationOptions
是静态的,我不能在其中使用this
关键字。 我也不能在 navigationOptions 中使用state
。 那么我如何使用ref
在按钮按下时获取输入文本。
编辑
我想从ref
获取TextInput
值
<TextInput ref={(ref) => { this.input = ref; }} />
// OR
<TextInput ref='input' />
这样我就可以从中获得它的价值
this.input._lastNativeText
// OR
this.refs['input']._lastNativeText
但是我不能在navigationOptions
使用this
关键字或state
,因为它是静态的。 如何在单击按钮时访问 TextInput 的值?
通过 naviagtion prop 向 navigationOptions 发送回调。 在 componentDidMount 中设置回调值
componentDidMount=()=> {
this.props.navigation.setParams({
onSubmitEditing: this.onSubmitEditing,
});
}
onSubmitEditing=(event)=>{
console.log(event);
//this is avaialbel here
}
从 naviagttion 参数获取 SubmitEdit 功能
static navigationOptions = ({ navigation = this.props.navigation }) => {
const onSubmitEditing = navigation.state.params.onSubmitEditing;
return {
headerTitle: (
<View style={{ width: '100%', height: 75, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 50, backgroundColor: 'white' }}>
<TextInput style={{ width: '85%', padding: 15 }}
onSubmitEditing={onSubmitEditing} />
<TouchableOpacity style={{ width: '15%', padding: 15 }}
onPress={() => navigation.navigate('Brands'/*, {text: HERE I WANT TO GET TEXT FROM REFERENCE}*/)}>
<Icon type='FontAwesome' name='search'
style={{ color: 'red', size: 20, textAlign: 'center' }} />
</TouchableOpacity>
</View>
)
}
};
以防万一有人需要这个
componentDidMount(){
---
this.props.navigation.setParams({
setMenuRef: this.setMenuRef.bind(this),
});
---
}
_menu = null;
setMenuRef = ref => {
this._menu = ref;
};
onSortClick() {
this._menu.show();
}
static navigationOptions = ({navigation}){
headerRight:(
---
ref={navigation.state.params && navigation.state.params.setMenuRef}
---
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.