慕慕森
为了更好地理解,我更改了组件的名称:// ChoicesHeaders.jsimport Checkbox from './CheckBox';const ChoicesHeaders = ({ headersName, choicesHeaderStyles, choicesHeaderItemStyles,}) => { return ( <View style={choicesHeaderStyles}> {headersName.map((header) => ( <View style={choicesHeaderItemStyles}> <Text>{header}</Text> </View> ))} </View> );};export default ChoicesHeaders;// Checkbox.jsconst Checkbox = ({ id, btnstyles, btnstylesSelect, checked, selectedIndex, onCheckboxChange,}) => { return selectedIndex !== id ? ( <TouchableOpacity style={btnstyles} onPress={() => { onCheckboxChange(id); }}></TouchableOpacity> ) : ( <TouchableOpacity style={btnstylesSelect} onPress={() => { onCheckboxChange(id); }}></TouchableOpacity> );};export default Checkbox;// Choice.jsimport Checkbox from './CheckBox';const Choice = ({ callback, text, btnstyles, btnTxtStyles, btnstylesSelect, btnTxtStylesSelect, onValueChange, choicesCount}) => { const [selectedIndex, setSelectedIndex] = React.useState(-1); const handleCheckboxChange = (id) => { setSelectedIndex(id) if (onValueChange) { onValueChange(text, id); } }; return ( <View style={{ flexDirection: 'row', alignItems: 'center' }}> <View style={btnTxtStyles}> <Text>{text}</Text> </View> {Array.from({length: choicesCount}).map((item, index) => ( <Checkbox id={index} btnstyles={btnstyles} btnstylesSelect={btnstylesSelect} selectedIndex={selectedIndex} onCheckboxChange={handleCheckboxChange} /> ))} </View> );};export default Choice;// App.jsimport Choice from './components/Choice';import ChoicesHeader from './components/ChoicesHeader';// or any pure javascript modules available in npmimport { Card } from 'react-native-paper';const data = [ { title: 'Instagram', /* extra properties(e.g. keys to save in db) */}, { title: 'Facebook', }, { title: 'Twitter', }, { title: 'Linkdin', },];const choicesHeaders=['1 hr', '2 hr', '3 hr', '4 hr'];export default function App() { const handleValueChange = (socialMediaName, checkboxId) => { // do what ever you want with this two }; return ( <View style={styles.container}> <ChoicesHeader headersName={choicesHeaders} choicesHeaderStyles={styles.choicesHeader} choicesHeaderItemStyles={styles.choicesHeaderItem} /> {data.map((x) => ( <Choice text={x.title} btnTxtStyles={styles.btnTxtStyles} btnstyles={styles.btnstyles} btnstylesSelect={styles.btnstylesSelect} onValueChange={handleValueChange} choicesCount={choicesHeaders.length} /> ))} </View> );}const checkBoxBaseStyles = { height: 40, width: 40, margin: 10,};const labelDimentions = { width: 100};const styles = StyleSheet.create({ btnstyles: { ...checkBoxBaseStyles, borderWidth: 1, borderColor: 'orange', }, btnstylesSelect: { ...checkBoxBaseStyles, backgroundColor: 'orange', }, btnTxtStyles: { ...labelDimentions, }, choicesHeader: { flexDirection: 'row', alignItems: 'center', marginLeft: labelDimentions.width }, choicesHeaderItem: { ...checkBoxBaseStyles, textAlign: 'center' },});