简体   繁体   English

在React Native中使用HOC时,传递一个TextInput,并且此TextInput不能被聚焦

[英]When using HOC in react native, pass a TextInput, and this TextInput cannot be focused

I'm use HOC try to pass a component and return a new component, it works, but when pass a TextInput, I found the TextInput cannot be focused 我正在使用HOC尝试传递一个组件并返回一个新的组件,它可以工作,但是当传递TextInput时,我发现TextInput无法聚焦

My react native version is 0.53.3 我的反应本机版本是0.53.3

and It blured after input one character 输入一个字符后模糊

when I run the code on react native 0.47.2 ,It even not able to be focused 当我在react native 0.47.2上运行代码时,甚至无法集中精力

Am I use HOC wrong? 我使用HOC错误吗?

here is my HOC function 这是我的HOC功能

const addTitle = Comp =>
   class extends React.PureComponent {
     render() {
       const { title, ...childProps } = this.props;
       return (
          <View style={{ paddingHorizontal: 20 }}>
             <View style={{ flexDirection: 'row', marginVertical: 5 }}>
             <Text style={styles.subText}>{title}</Text>
             <Text style={[styles.subText, { color: 'red' }]}>{'*'}</Text>  
             </View>
             <Comp {...childProps} />
          </View>
       );
     }
   };

this is how I use it 这就是我的用法

renderTitle = () => {
   const { title } = this.state;
   const Enhanced = addTitle(TextInput);
   return (
     <Enhanced
       autoCorrect={false}
       autoCapitalize={'none'}
       style={styles.textInput}
       title={'title'}
       value={title}
       onChangeText={this._onChangeText('title')}
     />
   );
 };

this is the onChangText function 这是onChangText函数

_onChangeText = attribute => value => {
   this.setState({
     [attribute]: value,
   });
};

Just move const Enganced = addTitle(TextInput) outside of the renderTitle method. 只需将const Enganced = addTitle(TextInput) renderTitle方法之外即可。 Like 喜欢

 const Enganced = addTitle(TextInput); class SomeComponent extends React.Component { // code } 

The problem is that, when the initialization is done within the render method, a new "function component" is created every time. 问题在于,当在render方法中完成初始化时,每次都会创建一个新的“功能组件”。 Therefore TextInput is not updated, but is re-created (the one with the focus is removed, and a new one is created). 因此,TextInput不会更新,而是会重新创建(具有焦点的那个被删除,并创建一个新的)。

Meanwhile, if the initialization (and declaration) is done in advance, only one "function component" is created and you get the benefit of react updating. 同时,如果预先进行了初始化(和声明),则仅创建一个“功能组件”,您将从反应更新中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM