[英]react native: what is the way to transform the class component to a function component with hooks?
what is the way to transform the class component to a function component with hooks ?将类组件转换为带有钩子的功能组件的方法是什么?
in my example i have a class component and i want transform it into function component, what is the way to do it ?在我的例子中,我有一个类组件,我想把它转换成函数组件,怎么做?
import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
export default class ExampleOne extends Component {
constructor(props) {
super(props);
this.state = {
tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
tableData: [
['1', '2', '3', '4'],
['a', 'b', 'c', 'd'],
['1', '2', '3', '456\n789'],
['a', 'b', 'c', 'd']
]
}
}
render() {
const state = this.state;
return (
<View style={styles.container}>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
<Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
)
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
Here is the class component to functional component conversion:这是类组件到功能组件的转换:
if you don't want to update state then you can remove setTableHead
and setTableData
from useState()
如果您不想更新状态,则可以从useState()
删除setTableHead
和setTableData
import React from 'react'
import { StyleSheet, View } from 'react-native'
import { Table, Row, Rows } from 'react-native-table-component'
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 },
})
const ExampleOne = () => {
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
Try this尝试这个
const ExampleOne = () => {
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']
]);
render() {
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.