javascript - 无法更改或使用 React Native 中导入的 TextInput 的属性
问题描述
我试图在 Formik 中使用创建的 TextField 组件,我创建了自己的名为 Input 的 TextField 组件并在表单中导入,但我无法更改它的任何道具或调用它的方法,如 style 或 onChangeText,我尝试使用的任何方法例如,使用 onChangeText 将不起作用。这是我来自组件和处方的代码。
这是我的输入组件的代码和我将其导入到的表单:
// Input Component
import React, { useState } from 'react';
import { TextInput, TextInputProps } from 'react-native';
import styles from '../../styles/styles';
interface InputProps extends TextInputProps{
value: string,
}
const Input: React.FC<InputProps> = ({value, ...rest}) => {
const [color, setColor] = useState("#f2f2f2");
return (
<TextInput
onFocus={() => setColor('#f9ffc4')}
onBlur={() => setColor('#f2f2f2')}
style={{
width: "70%",
minHeight: 40,
borderColor: styles.primaryColor,
borderBottomWidth: 1,
padding: 0,
borderRadius: 5,
marginBottom: 5,
backgroundColor: color,
}}
>
</TextInput>
)
}
export default Input;
// Form Page
import React from 'react';
import { Button, TextInput, View } from 'react-native';
import { Formik } from 'formik'
import Input from '../../../components/inputs/Input';
export default function FormikTest({ }) {
return (
<Formik
initialValues={{ input: '', teste: '' }}
onSubmit={values => console.log(values)}
>
{({ handleChange, handleSubmit, values }) => (
<View style={{ padding: 8, alignItems: 'center' }}>
<TextInput
style={{
margin: 10,
width: '50%',
height: 50,
borderWidth: 1,
borderColor: '#000',
}}
onChangeText={handleChange('input')}
value={values.input}
/>
<Input
onChangeText={() => { console.log('aqui') }}
value={values.teste}
/>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
)
}
解决方案
为了让您的自定义Input
识别您传递的道具,您必须指示它识别它们。像这样
const Input: React.FC<InputProps> = (props) => {
const [color, setColor] = useState("#f2f2f2");
return (
<TextInput
onFocus={() => setColor('#f9ffc4')}
onBlur={() => setColor('#f2f2f2')}
style={{
width: "70%",
minHeight: 40,
borderColor: styles.primaryColor,
borderBottomWidth: 1,
padding: 0,
borderRadius: 5,
marginBottom: 5,
backgroundColor: color,
}}
onChangeText={props.onChangeText}
autoFocus={props.autoFocus}
...
>
</TextInput>
)
}
export default Input;
对于你想要传递的每一个道具,你都必须将它添加到输入中,否则你自定义组件如何知道你想要从中得到什么?
推荐阅读
- django - Django 在后台定期运行函数
- spring-boot - BeanDefinitionStoreException - 如何克服它
- kotlin - 在回收站视图中保存和加载数据
- google-sheets - Google表格:如果单元格范围包含某个单词,则用文本填充单元格
- express - NextJS/Express 后端到 Vercel 的部署问题
- spring-boot - Liquibase 无法启动,因为在“迁移文件:类路径”中找不到更改日志
- swift - 用于 RSA 实现的 Swift 中的大数计算
- mongodb - 当我想使用 mongoose session transaction 使用 mongoose 的 updateMany() 函数时出现此错误
- mask - 不使用 COCO 权重的 MASK RCNN
- arrays - 如何快速在 Collectionview 中显示两个部分和行