gpt4 book ai didi

javascript - 父组件和子组件在react-native中同时渲染

转载 作者:行者123 更新时间:2023-12-02 22:22:50 29 4
gpt4 key购买 nike

我有一个父组件,它映射一系列章节并为找到的每个项目呈现(练习)一个子组件,并向其传递一组练习。

class ExercisesScreen extends Component {
showSelectedItemList = (screenName, text) => {
Navigation.push("ExercisesStack", {
component: {
name: screenName,
options: navOptionsCreator(text)
}
});
};

get chapters() {
return this.props.chapters.map(chapter => (
<TouchableOpacity key={chapter.id}>
<ExercisesList
onPress={() =>
this.showSelectedItemList(chapter.screenName, chapter.name)
}
exercises={chapter.exercises}
/>
</TouchableOpacity>
));
}

render() {
return <View>{this.chapters}</View>;
}
}

const mapStateToProps = state => ({
chapters: chaptersSelector(state)
});

当这个子组件接收到练习数组时,它会映射它并呈现练习列表。

class ExercisesList extends Component {
render() {
return this.props.exercises.map(exercise => (
<View key={exercise.id}>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.props.showSelectedItemList(exercise.screenName, exercise.name)
}
>
<Image source={exercise.icon}/>
<View>
<Text>{exercise.name}</Text>
</View>
<Image source={arrow} />
</TouchableOpacity>
<View />
</View>
));
}
}

ExercisesList.propTypes = {
onPress: PropTypes.func,
exercises: PropTypes.arrayOf(PropTypes.object)
};

我从同时渲染的两个组件中得到的结果:

enter image description here

问题是,我应该怎么做才能让它们单独渲染并在ExercisesScreen中显示每个章节对应的ExercisesList?

最佳答案

使您的子组件ExercisesList作为功能组件,仅显示每个章节对应的ExercisesList,不执行任何渲染。

如下:

const ExercisesList = (props) => {
const { exercises } = props;
return({
exercises.map(exercise, index) => renderExcercise(exercise, index)
})
}
const renderExcercise = (exercise, index) => {
return(
<View key={exercise.id}>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.props.showSelectedItemList(exercise.screenName, exercise.name)
}
>
<Image source={exercise.icon}/>
<View>
<Text>{exercise.name}</Text>
</View>
<Image source={arrow} />
</TouchableOpacity>
<View />
</View>
)
}
export default ExercisesList;

ExercisesList.propTypes = {
onPress: PropTypes.func,
exercises: PropTypes.arrayOf(PropTypes.object)
};

关于javascript - 父组件和子组件在react-native中同时渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170616/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com