Как вызвать значение родительского компонента в дочернем компоненте - PullRequest
0 голосов
/ 20 сентября 2018

Здравствуйте, я создаю реагировать родное приложение.В этом приложении домашняя страница содержит список проектов и кнопку фильтра.Когда я нажимаю кнопку фильтра, открывается экран фильтра, и этот экран содержит 3 раскрывающихся списка фильтров.Пользователь выберет значение из выпадающего списка и нажмет на кнопку фильтра.После того, как пользователь нажмет на страницу кнопки фильтра, он будет перенаправлен на домашнюю страницу, а список будет обновлен с новыми данными фильтра.Теперь я хотел передать значение фильтра дочернему компоненту домашней страницы, но я не понимаю, как отправить данные дочернему компоненту домашней страницы.Я могу получить все свои значения фильтра в окне консоли, но я не знаю, как мне передать это значение для отображения новых данных в компоненте.

Вот мой код:

HomeScreen.js

      render() {
    return (
      <View style={styles.container}>
        <HomeProject />
        <View>
          <TouchableHighlight
            style={styles.addButton}
            underlayColor='#ff7043' onPress={() => NavigationService.navigate('Filters', { filterCallback: filterValue => this.onFilterCallback(filterValue) })}>
            <Text style={{ fontSize: 20, color: 'white' }}>+</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }
   onFilterCallback(filterValue) {
        console.log('-> Callback value:', filterValue);
        this.setState({ filterValue: filterValue });
      }

HomeProject.js

class HomeProject extends Component {
  constructor(props) {
    super(props)
  }

  componentWillMount() {
   this.props.fetchProjectList();
    this.createDataSource(this.props);
  }

  componentWillReceiveProps(nextProps) {
    console.log('nextProps' + JSON.stringify(nextProps));
    console.log('receive' + JSON.stringify(nextProps.filterValue));
     this.createDataSource(nextProps);
  }

  createDataSource({ projectlist }) {
    console.log('111');
    console.log('projetclist' + projectlist);
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });

    this.dataSource = ds.cloneWithRows(projectlist);
  }

  renderRow(data) {
    console.log('222');
    const { currentUser } = firebase.auth();
  //  if (data.userid !== currentUser.uid && !data.isDraft) {
        return (<ProjectList data={data} />);
  //  }

  }

  render() {
    return (
      <View style={{ flex: 1 }}>
          <ListView
            style={{ flex: 1 }}
            dataSource={this.dataSource}
            renderRow={this.renderRow}
          />
      </View>
    );
  }
}

FilterScreen.js

 onGoBack() {
    console.log('Filter is in going back');
    const { userprofile } = this.props;
    const { type } = userprofile;
      console.log('type :' + type);

        const ref = firebase.database().ref('projects');
        const query = ref.orderByChild('type').equalTo(type);
        query.on('value', (snapshot) => {
          console.log('project detail ', snapshot.val());

          const filterProjects = [];

          snapshot.forEach((item) => {
            filterProjects.push({ key: item.key, 
              userid: item.val().userid,
              title: item.val().title,
              location: item.val().location
            });
          });
          console.log("filterProjects: ", filterProjects);


        if (this.params && this.params.filterCallback) this.params.filterCallback(filterProjects);
        console.log('goback');
        this.props.navigation.goBack();

  }


    renderButton() {
    return (
      <Button
        style={{ alignItems: 'center' }}
        onPress={this.onGoBack.bind(this)}
      >
        Filter
      </Button>
    );
  }
 render() {
const { navigate } = this.props.navigation

  return (
      <ScrollView style={{ flex: 1, backgroundColor: '#ffffff' }}>
          {this.renderLoading()}

            <DropDown
                label="Project Type"
                containerStyle={{
                  width: 100,
                  //zIndex: 60,
                  top: 20,

                  }}
                onValueChange={(value) => this.props.userProfile({ prop: 'type', value })}
                selectedValue={this.props.userprofile.type}
              >
                {Object.keys(this.props.types).map((key) => {

                    return (<Picker.Item
                      label={this.props.types[key]}
                      value={this.props.types[key]}
                      key={key}
                    />);
                })}
            </DropDown>

            <DropDown
              label="Language"
              containerStyle={{
                width: 140,
                //zIndex: 60,
                top: 20,

                }}
              onValueChange={(value) => this.props.userProfile({ prop: 'category', value })}
              selectedValue={this.props.userprofile.category}
            >
              {Object.keys(this.props.categories).map((key) => {

                  return (<Picker.Item
                    label={this.props.categories[key]}
                    value={this.props.categories[key]}
                    key={key}
                  />);
              })}
            </DropDown>

            <DropDown
              label="Keywords"
              containerStyle={{
                width: 140,
                //zIndex: 60,
                top: 20,

                }}
              onValueChange={(value) => this.props.userProfile({ prop: 'category', value })}
              selectedValue={this.props.userprofile.category}
            >
              {Object.keys(this.props.categories).map((key) => {

                  return (<Picker.Item
                    label={this.props.categories[key]}
                    value={this.props.categories[key]}
                    key={key}
                  />);
              })}
            </DropDown>

            <CardSection style={styles.filterBtnStyle}>
            {this.renderButton()}
            </CardSection>
      </ScrollView>
    );
  }

1 Ответ

0 голосов
/ 20 сентября 2018

Почему бы вам просто не использовать реквизиты, чтобы передать свой filterValue дочернему компоненту?

В вашем HomeScreen.js:

<HomeProject filterValue={this.state.filterValue}/>

И затем вы можете получить к нему доступ в своемКомпонент HomeProject с:

this.props.filterValue

Вы можете передавать в качестве реквизитов все, что хотите, и использовать их в дочерних компонентах.Когда setState вызывается в родительском компоненте, он заставляет переопределить дочерние элементы с новым значением.

Подробнее о реквизитах можно прочитать в документации Facebook: https://facebook.github.io/react-native/docs/props

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...