我在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
来获得按钮按下时的输入文本。
编辑
我想从TextInput
获得ref
的价值
<TextInput ref={(ref) => { this.input = ref; }} />
// OR
<TextInput ref='input' />
这样我就可以从中获取价值
this.input._lastNativeText
// OR
this.refs['input']._lastNativeText
但是我不能使用this
关键字或state
中的navigationOptions
,因为它是静态的。如何在单击按钮时访问TextInput的值?
答案 0 :(得分:0)
通过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>
)
}
};
答案 1 :(得分:0)
以防万一有人需要
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}
---
)
}