React Native TextInput 失去了对来自 useState 的调用挂钩的关注

React Native TextInput loses focus on call hook from useState

环境

本机反应:“0.61.5”,

"styled-components": "4.4.1"

复制

小吃示例:https://snack.expo.io/BJSfYqlCS

import * as React from 'react';
import styled from 'styled-components'
import {View} from 'react-native'

export default () => {
  const [text, setText] = React.useState('');

  const StyledInput = styled.TextInput`
    background-color: red;
    border-color: black;
  `

  return (
    <View>
      <StyledInput value={text} onChangeText={text => setText(text)} />
    </View>
  );
}

重现步骤

在样式化的 TextInput 中输入内容

预期行为

只需简单输入

实际行为

失去焦点

所以这个问题很棘手,看起来问题是你在它的父 return 方法中定义了 StyledInput,然后直接调用父的 setText 方法(而不是通过道具),这会导致您不想要的重新渲染。

更好的方法是使用直接文本输入并对其应用样式。请参阅下面的代码,我还在 expo snack 中分享了一个工作示例。请检查一下。

import * as React from 'react';
import styled from 'styled-components'
import {TextInput,View} from 'react-native';

export default () => {
  const [text, setText] = React.useState('');

  const StyledView = styled.View`
    flex: 1;
    align-items:center;
    justify-content: center;
    background-color: papayawhip;
  `

  const StyledInput = styled.TextInput`
    background-color: white;
  `

  const StyledText = styled.Text`
    color: palevioletred;
  `

  return (
    <View>
      <StyledText>Hello World!</StyledText>
      <TextInput style={{height:50,width:50,backgroundColor:'red'}} value={text} onChangeText={text => setText(text)} />
    </View>
  );
}

世博小吃expo url

希望对您有所帮助。有疑问请随意

从函数中获取样式

import * as React from 'react';
import styled from 'styled-components'
import {View} from 'react-native'

const StyledInput = styled.TextInput`
    background-color: red;
    border-color: black;
  `

export default () => {
  const [text, setText] = React.useState('');

  return (
    <View>
      <StyledInput value={text} onChangeText={text => setText(text)} />
    </View>
  );
}

勾选expo shack