如何使用onChange自定义文本输入反应原生



所以我是react native的新手,我建立了一个自定义文本输入,通过遵循教程给出建议。但是现在我不能在自定义文本输入中使用onChange。我试图在App.js中创建一个状态,并在AutoCompleteText.js文件中更改它,但没有工作。我如何在我的自定义文本输入中获得值?

my App.js file:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import AutoCompleteText from './AutoCompleText'
import './AutoCompleteText.css';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.AutoComp}>
<AutoCompleteText items={['Ali','Veli','Ahmet']} />
</View>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
AutoComp:{
width:600
}
});

my AutoCompleteText.js文件

import React from 'react'
import './AutoCompleteText.css';
export default class AutoCompleteText extends React.Component{

constructor(props){
super(props);
this.state={
suggestions:[],
text:'',

};
}

onTextChanged = (e) =>{
const {items} = this.props;
const value = e.target.value;
let suggestions = [];
if (value.length > 0){
const regex = new RegExp(`^${value}`,'i');
suggestions = items.sort().filter(v => regex.test(v));


}
this.setState(() => ({ suggestions , text: value }));
}

suggestionSelected(value){
this.setState(() =>({
text: value,
suggestions:[],
}) )
}

renderSuggestions(){
const {suggestions} = this.state;
if (suggestions.length === 0){
return null;
}
return(
<ul>
{suggestions.map((item) => <li onClick={() => this.suggestionSelected(item)}>{item}</li>)}
</ul>
);
}


render(){
const { text } = this.state;
return(
<div className="AutoCompleteText">
<input value={text} onChange={this.onTextChanged} type ='text'/>
{this.renderSuggestions()}

</div>

)

}
}

嗨Ülkü Tuncer kktaek,你写错了语法。你把react native的语法和react混在一起了。在react native中,你应该使用textinput组件(docs中的内置组件)。

react native textput的语法如下

import React from 'react';
import { TextInput } from 'react-native';
const UselessTextInput = () => {
const [value, onChangeText] = React.useState('Useless Placeholder');
return (
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={value}
/>
);
}
export default UselessTextInput;

相关内容

  • 没有找到相关文章