如何为我的组件触发此函数(React Native)?

时间:2017-03-09 14:44:26

标签: reactjs react-native

我有一段

的组件代码
   class List extends Component {       
   ...

   render() {
    ...
    return
     <TouchableHighlight onPress={()=>this.props.clearFilter()}>
     </TouchableHighlight>
    ...
    }
   ...
   }

父母:

    class Nav extends Component {
     ...
     // render implements renderscene for navigator

     renderScene(route, navigator){
     ...
     return (
     <List 
       navigator={navigator}
       clearFilter={this.props.clearFilter}
       ref={component => this._list = component}/>
     );
     }

export default class App extends Component {

applyfilter(){
//...
}

  constructor(props){
      ...
      this.applyfilter = this.applyfilter.bind(this);
  }
  clearFilter(){
    this.setState(
      {
        _filter:null,
        _filterValue:"",
      }, ()=>{this.applyFilter();}
    );

  _renderScene = ({ route }) => {
      return <Nav ref={component => this._nav = component} clearFilter={this.clearFilter.bind(this)}/>;
...

}

所以我将clearFilter()函数从App传递到Nav,Nav将它传递给List。当按下列表按钮时,我想要触发应用程序的clearFilter(),但由于某种原因它不会计算为函数。

每次按下按钮,我都会undefined is not a function (evaluating '_this3.applyFilter()')

如何从List的按钮触发clearFilter for App?

3 个答案:

答案 0 :(得分:1)

只是一个错字错误:您正在创建applyfilter函数,但是您在applyFilter函数中将其调用为clearFilter。这就是为什么它会抛出错误undefined

答案 1 :(得分:0)

假设您在此处没有遗漏某些代码,getIArray()[i]似乎没有在任何地方定义。

答案 2 :(得分:0)

您的代码格式不清晰。看起来你已经在类之外声明了applyFilter。在类中的构造函数之后定义它。

我个人更喜欢使用clearFilter={()=> {this.clearFilter()}}代替clearFilter={this.clearFilter.bind(this)}

applyFilter相同。

&#13;
&#13;
class Button extends Components {
  render(){
    return(
      <TouchableOpacity
        onPress={()=>{ this.props.clearFilter() }}
      >
      </TouchableOpacity>
    );
  }
}

class List extends Components {
  render(){
    return(
      <Button
        clearFilter={()=>{ this.props.clearFilter() }}
      />
    );
  }
}

export default class Mainapp extends Components {
  constructor(props){
    super(props);
    this.state = {};
  }

  clearFilter(){
    //// do something
    this.applyFilter();
  }

  applyFilter(){
    //// do something
  }

  render(){
    return(
      <View>
        <List
          clearFilter={()=>{ this.clearFilter() }}
        />
      </View>
    );
  }
}
&#13;
&#13;
&#13;