react-native - React Native StackNavigator Reference Null on Props
问题描述
我正在使用@react-navigation/stack
在我们的应用程序上使用它。我们有一个问题,在导航到 Detail 组件后,我们需要导航回 Main 组件,Detail 组件有一个 Reference 用于输入以将焦点放在挂载上。
所以我们有这个。
const input = React.createRef();
class Barcode extends React.Component {
componentDidMount() {
if(this.input){
setTimeout(() => {
this.input.current.focus();
}, 400);
}
}
moveUpdate() {
const { barcodeReducerMessageVisible, barcodeReducerMessage, barcodeReducerMessageFinished } = this.props;
if(barcodeReducerMessageFinished) {
this.props.navigation.navigate('Search');
}
}
render() {
return ( <ScrollView keyboardShouldPersistTaps={'handled'}>
<Input
label="Código de barras"
placeholder="Código de barras"
errorStyle={{ color: "red" }}
inputStyle={{ marginTop: 40, marginBottom: 40 }}
onChangeText={textBarcode => this.setState({ textBarcode })}
value={textBarcode}
ref={(ref)=>{this.input = ref}}
onBlur={() => this.Save()}
/> </ScrollView> );
}
}
所以 moveUpdate 导航到“搜索”,在搜索时我们有这样的东西:
ChangeBarCode(stockidRewn = null) {
this.props.navigation.navigate('Barcode', { stockidRewn } ,{ stockidRewn: stockidRewn });
}
<ListItem
leftAvatar={{ source: { uri: searchProductReducerRepos[key].vtiger_productid } }}
key={key}
title={searchProductReducerRepos[key].description}
subtitle={description}
bottomDivider
onPress={() => this.ChangeBarCode(searchProductReducerRepos[key].stockid)}
/>
当我再次调用 onPress 去 Barcode 时,我得到:
TypeError: undefined is not an object (_this.input.current.focus)
我不知道引用是否没有正确声明。
有什么建议吗?
解决方案
您应该在组件内定义 ref
class Barcode extends React.Component {
// declaring ref inside the component
input = React.createRef();
componentDidMount() {
if (this.input) {
setTimeout(() => {
this.input.current.focus();
}, 400);
}
}
moveUpdate() {
const { barcodeReducerMessageVisible, barcodeReducerMessage, barcodeReducerMessageFinished } = this.props;
if (barcodeReducerMessageFinished) {
this.props.navigation.navigate('Search');
}
}
render() {
return (<ScrollView keyboardShouldPersistTaps={'handled'}>
<Input
label="Código de barras"
placeholder="Código de barras"
errorStyle={{ color: "red" }}
inputStyle={{ marginTop: 40, marginBottom: 40 }}
onChangeText={textBarcode => this.setState({ textBarcode })}
value={textBarcode}
ref={(ref) => { this.input = ref }}
onBlur={() => this.Save()}
/> </ScrollView>);
}
}
推荐阅读
- javascript - 我应该为 oauth2 使用 camelCase 吗?
- xml - 使用 XQuery/XPath 获取祖先节点的相反顺序
- vue.js - 未知的自定义元素
? - android - 如何使用房间数据库获取表的最后一条记录
- flutter - 在 modalBottomSheet 中调用函数时更改有状态小部件中的变量
- objective-c - 如何与 Socket.io 连接?在目标 c 中使用 Swift 5 中的 socket.io
- arrays - React Hooks - 动态渲染文本输入并将输入存储为一个数组
- windows - 如何在 for 循环的每次迭代后向字符串添加字符?
- android - 无法弄清楚如何将此字段保存到 Android 房间的数据库中
- oracle - 变异,触发器/函数在使用触发器时可能看不到错误