reactjs - 父元素未获取子函数调用参数

标签 reactjs react-native

我就快到了,只是缺少一件简单的事情。我正在修改父级的状态以及已通过函数的子级。问题是,当子进程使用参数调用从父进程传递的函数时,该参数不会在父进程的方法中被捕获。

父级:

export default class GameList extends Component {
  constructor({ navigation }) {
    super();
    this.navigation = navigation;
    this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    this.state = {
      test: 0,
    }

  updateState(filteredResults) {
    this.setState((prevState) => ({
      dataSource: this.ds.cloneWithRows(filteredResults),
    }));
  }
  render() {
    return (
      <View style={styles.background}>
        <Header updateState={() => { this.updateState() }} dataSet={this.dataSet} />
      </View >
    )
  }

};

child :

import React, { Component } from 'react';
import { View, TextInput } from 'react-native';

import styles from './styles';

class Header extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder="Search..."
          onChangeText={(text) => {
            const filteredResults = this.filterRows(text, this.props.dataSet);
            debugger;
            this.props.updateState(filteredResults);
          }}
        />
      </View>
    );
  }

  filterRows(searchText, dataSet) {
    return dataSet.filter((record) => record.title.includes(searchText));
  }
}


export default Header;

父级中的“filteredResults”未定义。

最佳答案

原因是您在不带参数的情况下调用该方法:

updateState={() => { this.updateState() }} //here

而不是这样写:

updateState={this.updateState}

并使用 updateState 函数,如下所示:

updateState = (filteredResults) =>  {
     this.setState((prevState) => ({
        dataSource: this.ds.cloneWithRows(filteredResults),
     }));
 }

或者另一种选择是在构造函数中定义绑定(bind):

this.updateState = this.updateState.bind(this);

然后像这样使用该函数:

updateState={this.updateState}

updateState(filteredResults) {
     this.setState((prevState) => ({
        dataSource: this.ds.cloneWithRows(filteredResults),
     }));
 }

关于reactjs - 父元素未获取子函数调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709915/

相关文章:

javascript - React 中可以有组件接口(interface)吗?

css - ReactCSSTransitionGroup 的麻烦 - 试图获得平滑的滑入/滑出动画

javascript - react native 安全 Android

react-native - 如何在来自映射函数的组件之间添加空间?

react-native - 无法解析模块 'react-navigation'

javascript - 如何在 react Material 表中创建自定义过滤器框?

javascript - 如何在 React Native 中使用引用更改 TextInput 的值?

react-native - React Native、Fetch 和 Dispatch : How do I access responseData within mapDispatchToProps()?

javascript - 无法在 react 中访问数组元素

facebook - 网络关闭时如何处理 React-Native 中的网络故障