【发布时间】:2018-06-25 14:14:06
【问题描述】:
我正在尝试以编程方式聚焦 TextInput 元素,在它安装后有一定的延迟,我有以下组件(显示输入和按钮的视图)
由于某种原因,这会出错
_this2.inputRef.focus 不是函数
我不知道为什么。一个不合适的事情是我得到流说React 上不存在createRef(),但我假设这只是缺少流定义,因为我正在使用react 16.3.1,这是在 16.3 中添加的,加上调用时没有错误。
// @flow
import React, { Component, Fragment } from 'react'
import Button from '../../composites/Button'
import TextInput from '../../composites/TextInput'
import OnboardingStore from '../../store/OnboardingStore'
import withStore from '../../store'
import { durationNormal } from '../../services/Animation'
/**
* Types
*/
export type Props = {
OnboardingStore: OnboardingStore
}
/**
* Component
*/
class CharacterNameView extends Component<Props> {
componentDidMount() {
this.keyboardTimeout = setTimeout(() => this.inputRef.focus(), durationNormal)
}
componentWillUnmount() {
clearTimeout(this.keyboardTimeout)
}
keyboardTimeout: TimeoutID
inputRef = React.createRef()
render() {
const { OnboardingStore } = this.props
return (
<Fragment>
<TextInput
ref={this.inputRef}
enablesReturnKeyAutomatically
value={OnboardingStore.state.username}
onChangeText={username => OnboardingStore.mutationUsername(username)}
placeholder="Username"
blurOnSubmit
returnKeyType="done"
onSubmitEditing={/* TODO */ () => null}
/>
<Button disabled={!OnboardingStore.state.username} color="GREEN" onPress={() => null}>
Create
</Button>
</Fragment>
)
}
}
export default withStore(OnboardingStore)(CharacterNameView)
我使用的TextInput组件是从这个文件导入的
// @flow
import React, { Component } from 'react'
import { StyleSheet, TextInput as Input } from 'react-native'
import RatioBgImage from '../components/RatioBgImage'
import { deviceWidth } from '../services/Device'
/**
* Types
*/
export type Props = {
style?: any
}
/**
* Component
*/
class TextInput extends Component<Props> {
static defaultProps = {
style: null
}
render() {
const { style, ...props } = this.props
return (
<RatioBgImage source={{ uri: 'input_background' }} width={70} ratio={0.1659}>
<Input
{...props}
placeholderTextColor="#4f4a38"
selectionColor="#797155"
autoCapitalize="none"
autoCorrect={false}
keyboardAppearance="dark"
style={[styles.input, style]}
/>
</RatioBgImage>
)
}
}
export default TextInput
/**
* Styles
*/
const styles = StyleSheet.create({
input: {
width: '96.4%',
height: '97.45%',
color: '#797155',
fontSize: deviceWidth * 0.043,
marginLeft: '1%',
paddingLeft: '5%'
}
})
下面是this.innerRef 的样子,我目前看不到任何焦点属性
【问题讨论】:
-
试试
this.inputRef.current.focus() -
或者通过传入
TextInput的引用使用React.findNodeHandle找到TextInput的节点句柄 -
旧版本的功能引用是否有效?
-
我还注意到您的
TextInput是从另一个文件导入的。您也可以发布该代码吗? -
@bennygenel 完全忘记了这部分,我将它添加到问题中,但是它将所有道具(如 ref)传递给 react-native 输入
标签: javascript reactjs react-native