[英]Can't change or use properties from imported TextInput in React Native
我试图在 Formik 中使用创建的 TextField 组件,我创建了自己的名为 Input 的 TextField 组件并导入到表单中,但我无法更改它的任何道具或调用它的方法,如样式或 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;
对于你想要传递的每个道具,你必须将它添加到输入中,否则你的自定义组件如何知道你想要从中得到什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.