[英]What is the way to transform my class component into function component?
What is the way to transform my class component into function component?将我的类组件转换为功能组件的方法是什么? in my example I try to display search bar and i need do it with function component instead class component.
在我的示例中,我尝试显示搜索栏,我需要使用函数组件而不是类组件来完成。
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 }
});
Probably you can try as the following:也许你可以尝试如下:
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;
I suggest the following documentation to read in more details: Using the State Hook我建议阅读以下文档以了解更多详细信息: Using the State Hook
+1 addition: +1 加成:
I would consider using const [search, setSearch] = useState('')
only for your search state because it is shorter.我会考虑将
const [search, setSearch] = useState('')
仅用于您的搜索状态,因为它更短。 In the mentioned way you can store more information in the search
state but it's up to you which fits for your situation better.以上述方式,您可以在
search
状态中存储更多信息,但这取决于您是否更适合您的情况。
You use React Hook and change your class-based component to functional component您使用 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;
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}
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.