将类组件转换为函数组件的方法是什么? 在我的示例中,我尝试显示搜索栏,我需要使用功能组件而不是类组件来实现。
import React, { useState} from 'react';
import { StyleSheet, View } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
const ExampleOne = (props) =>{
const [tableHead, settableHead] = useState(['Head', 'Head2', 'Head3', 'Head4'])
const [tableData,settableData] = useState([
['1', '2', '3', '4'],
['a', 'b', 'c', 'd'],
['1', '2', '3', '456\n789'],
['a', 'b', 'c', 'd']
])
return (
<View style={styles.container}>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
<Row data={tableHead} style={styles.head} textStyle={styles.text}/>
<Rows data={tableData} textStyle={styles.text}/>
</Table>
</View>
)
export default ExampleOne
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
答案 0 :(得分:0)
可能您可以尝试以下操作:
import React, { useState } from 'react';
import { SearchBar } from 'react-native-elements';
const App = () =>
const [search, setSearch] = useState({
text: ''
});
return {
return (
<SearchBar
placeholder="Type Here..."
onChangeText={ (search) => setSearch({ text: search }) }
value={search.text}
/>
);
}
}
export default App;
我建议您阅读以下文档以了解更多详细信息:Using the State Hook
+1添加:
我会考虑仅将const [search, setSearch] = useState('')
用于您的搜索状态,因为它更短。通过上述方式,您可以在search
状态下存储更多信息,但是这取决于您自己,更好地适合您的情况。
答案 1 :(得分:0)
您使用React Hook并将基于类的组件更改为功能组件
import React, { useState } from "react";
import { SearchBar } from "react-native-elements";
const App = () => {
const [search, setSearch] = useState("");
const updateSearch = (search) => {
setSearch(search);
};
return (
<SearchBar
placeholder="Type Here..."
onChangeText={(i) => updateSearch(i)}
value={search}
/>
);
};
export default App;
答案 2 :(得分:0)
import React, { useState } from 'react';
import { SearchBar } from 'react-native-elements';
export default App = () => {
const [search, setSearch ] = useState('');
return(
<SearchBar
placeholder="Type Here..."
onChangeText={ search => setSearch(search) }
value={search}
/>
);
}