у меня есть панель поиска в контейнере, я устанавливаю состояние «поиск» при изменении текста.. и я хочу передать это состояние вложенному компоненту (в отдельном документе), чтобы он мог фильтровать отображаемые изображения на основе состояния поиска.
я пробовал везде искать и импортировать/экспортировать поиск. Я также бесконечно гуглил это и не мог найти ничего, относящегося к проблеме. может у меня не правильная терминология.
В папке Components есть папка AppTabNavigator, которая содержит этот файл под названием HomeTab.js. Я пытаюсь передать состояние из HomeTab.js в CardComponent.js, вставленное ниже.
import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import { Container, Content, Icon } from 'native-base';
import CardComponent from '../CardComponent';
import { SearchBar } from 'react-native-elements';
class HomeTab extends Component {
static navigationOptions = {
tabBarIcon: ({ tintColor }) => (
<Icon name = "ios-search" style = {{ color: tintColor }} />
)
};
state = {
search: ''
};
updateSearch = search => {
this.setState({ search });
console.warn(search);
};
render() {
const { search } = this.state;
return (
<Container style = {styles.container}>
<SearchBar
containerStyle = {{ backgroundColor: 'transparent' }}
placeholder = "Filter for..."
placeholderTextColor = "white"
onChangeText = {this.updateSearch}
value = {search}
/>
<Content>
<CardComponent search = {this.state.search} />
</Content>
</Container>
);
}
}
export default HomeTab;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black'
}
});
Папка Components, содержащая папку AppTabNavigator, также содержит этот файл с названием CardComponent.js... Я пытаюсь передать состояние в CardComponent.js из HomeTab.js
import React, { Component } from 'react';
import { View, Dimensions, Image, Text, TouchableOpacity } from 'react-native';
var images = [
require('../assets/IMG-0028.jpeg'),
require('../assets/IMG-0048.jpeg'),
require('../assets/IMG-0064.jpeg'),
require('../assets/IMG-0089.jpeg'),
require('../assets/IMG-0119.jpeg'),
require('../assets/IMG-0151.jpeg'),
require('../assets/IMG-0152.jpeg'),
require('../assets/IMG-0153.jpeg'),
require('../assets/IMG-0154.jpeg'),
require('../assets/IMG-0155.jpeg'),
require('../assets/IMG-0184.jpeg'),
require('../assets/IMG-0221.jpeg'),
require('../assets/IMG-0268.jpeg'),
require('../assets/IMG-0309.jpeg'),
require('../assets/IMG-0320.jpeg'),
require('../assets/IMG-0474.jpeg'),
require('../assets/IMG-0707.jpeg'),
require('../assets/IMG-0860.jpeg')
];
var { width, height } = Dimensions.get('window');
class CardComponent extends Component {
renderHome = () => {
console.info(search);
return images.map((image, index) => {
return (
<TouchableOpacity onPress = {() => console.warn(index)} key = {index}>
<View
key = {index}
style = {[
{ width: width / 3 },
{ height: height / 3 },
{ marginBottom: 2 },
index % 3 !== 0 ? { paddingLeft: 2 } : { paddingLeft: 0 }
]}
>
<Image
style = {{ flex: 1, width: undefined, height: undefined }}
source = {image}
/>
</View>
</TouchableOpacity>
);
});
};
render() {
return (
<View style = {{ flexDirection: 'row', flexWrap: 'wrap' }}>
{this.renderHome()}
</View>
);
}
}
export default CardComponent;
Ожидается, что я смогу искать свои изображения по идентификатору, чтобы затем научиться помечать их в приложении и искать эти теги. Фактическими результатами были разочарование и потерянное время.
Кажется, это имеет смысл. Но я не могу заставить console.info(search) работать с CardComponent.js, что указывает на то, что он не получает информацию.
Что вы получаете в console.info?
ReferenceError: не удается найти переменную: поиск
Можете ли вы обновить код, чтобы он включал console.info?
Конечно, сделано. Я обновил оба файла.
class CardComponent extends Component {
renderHome = () => {
console.info(this.props.search);
return images.map((image, index) => {
return (
<TouchableOpacity onPress = {() => console.warn(index)} key = {index}>
<View
key = {index}
style = {[
{ width: width / 3 },
{ height: height / 3 },
{ marginBottom: 2 },
index % 3 !== 0 ? { paddingLeft: 2 } : { paddingLeft: 0 }
]}
>
<Image
style = {{ flex: 1, width: undefined, height: undefined }}
source = {image}
/>
</View>
</TouchableOpacity>
);
});
};
render() {
return (
<View style = {{ flexDirection: 'row', flexWrap: 'wrap' }}>
`{this.renderHome.bind(this)()}`
</View>
);
}
}
export default CardComponent;
Прекрасный! Спасибо большое. у вас случайно нет быстрого решения для рендеринга результатов поиска вместо всего массива, не так ли?
Я доволен. Я постараюсь найти время. Никаких обещаний... В случае, если я этого не сделаю, удачи :)
Я не вдавался во все подробности, поэтому могу что-то упустить... Если вы хотите передать состояние в CardComponent, почему бы вам не написать в HomeTab: <CardComponent search = {this.state.search} /> ?