通过钩子将类组件转换为功能组件的方法是什么?
在我的示例中,我有一个类组件,我想将其转换为功能组件,该怎么做?
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 }
});
答案 0 :(得分:1)
尝试一下
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;
答案 1 :(得分:1)
以下是类组件到功能组件的转换:
如果您不想更新状态,则可以从setTableHead
删除setTableData
和useState()
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