【问题标题】:React Native TextInput loses focus on call hook from useStateReact Native TextInput 失去了对来自 useState 的调用钩子的关注
【发布时间】:2020-04-06 13:14:49
【问题描述】:
环境
react-native: "0.61.5",
“样式化组件”:“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 中输入一些内容
预期行为
简单的打字
实际行为
失去焦点
【问题讨论】:
标签:
react-native
react-hooks
styled-components
【解决方案1】:
从函数中获取样式
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
【解决方案2】:
所以问题很棘手,看起来问题是你在它的父返回方法中定义你的 StyledInput,然后直接调用父的 setText 方法(而不是通过道具),这会导致你没有重新渲染不想。
更好的方法是使用直接文本输入并对其应用样式。请参阅下面的代码,并且我在 expo 小吃中分享了一个工作示例。检查一下。
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
希望对您有所帮助。如有疑问,请随意