在我的应用中,我在不同的标签中有两个组件:书架和 AddBook 。 BookShelf包含一个由用户添加的书籍的FlatList,我对AddBook的想法是搜索书籍,然后按一个按钮将其添加到BookShelf组件的列表中。
我的想法是将书籍作为对象存储在BookShelfs状态的数组中。是否可以从AddBook访问BookShelf的状态,我该怎么做?我试图在BookShelf中创建一个更新状态并将其作为道具传递给我的AddBook组件的函数,但没有成功,因为我必须在BookShelf中渲染AddBook组件以传递道具。
现在,我在选项卡上使用TabNavigator,在选项卡中嵌套了单独的StackNavigator。
树结构:
开始: App.js-> TabsNavigator-> TABS: BookShelf&AddBook
选项卡1: BookShelf-> STACK: BookShelfStack-> 组件: BookShelf和BookInfo
TAB 2: AddBook-> 堆栈: AddBookStack-> 组件: AddBook
Router.js处理导航:
export const BookShelfStack = createStackNavigator({
BookShelf: {
screen: BookShelf,
navigationOptions: {
title: 'Book Shelf',
}
},
BookInfo: {
screen: BookInfo,
navigationOptions: {
title: 'Book Info'
}
},
})
export const AddBookStack = createStackNavigator({
AddBook: {
screen: AddBook,
navigationOptions: {
title: 'Add Book',
}
}
})
export const TabsNavigator = createMaterialTopTabNavigator({
'BookShelf': {
screen: BookShelfStack,
navigationOptions: {
tabBarLabel: 'Book Shelf',
tabBarIcon: ({tintColor}) => <Icon name="ios-book" type="ionicon" size={28} color={tintColor}/>
}
},
'AddBook': {
screen: AddBookStack,
navigationOptions: {
tabBarLabel: 'Add Book',
tabBarIcon: ({tintColor}) => <Icon name="ios-add-circle-outline" type="ionicon" size={28} color={tintColor}/>
}
},
});
带有占位符数据的BookShelf组件:
export default class BookShelf extends Component {
constructor(props) {
super(props);
this.addBook = this.addBook.bind(this);
this.state = {
books: [
{
id: 1,
title: 'Harry Potter and the Goblet of Fire',
author:'J.K. Rowling',
thumbnail:'https://covers.openlibrary.org/w/id/7984916-M.jpg',
},
{
id: 2,
title: 'The Hobbit',
author: 'J.R.R. Tolkien',
thumbnail:'https://covers.openlibrary.org/w/id/6979861-M.jpg'
},
{
id: 3,
title: '1984',
author: 'George Orwell',
thumbnail:'https://covers.openlibrary.org/w/id/7222246-M.jpg'
}
]
}
}
renderBook = ({item}) => (
<BookShelfItem
navigation={this.props.navigation}
id={item.id}
title={item.title}
author={item.author}
thumbnail={item.thumbnail}
/>
);
addBook(book) {
let updatedBookList = this.state.books.slice();
updatedBookList.push(book);
this.setState({
books: updatedBookList
});
}
render() {
const {container} = styles;
<AddBook addBook={this.addBook}/>
return (
<View style={container}>
<StatusBar barStyle="light-content"/>
<FlatList
data={this.state.books}
keyExtractor={(item, index) => item.id.toString()}
renderItem={this.renderBook}
extraData={this.state.books}
/>
</View>
);
}
}
AddBook组件,我尝试从BookShelf接收prop的addBook函数:
export default class AddBook extends Component {
constructor(props) {
super(props)
}
render() {
const {container, title, textInputStyle} = styles;
const { addBook } = this.props;
return (
<View style={container}>
<Text style={title}>
Add Book
</Text>
<TextInput style={textInputStyle}
placeholder = {'Search books..'}
/>
<Button
title = "Add book"
onPress={() => addBook}
/>
</View>
);
}
}