问题描述:

I have two very simple classes. All I am trying to do is call a method from another component that will print text to the console. When the user clicks the navigate button in class 2, it should call the _printtest function in class 1, unfortunately, that is not happening.

Class 1

 class drawerControl extends Component {

constructor(props) {

super(props);

this._printtest = this._printtest.bind(this);

};

_printtest(){

console.log("Hello World");

}

render() {

return (

<Home

openControlPanel={this.openControlPanel.bind(this)}

functest={this._printtest}>

</Home>

);

}

}

Class 2

class Home extends Component {

constructor(props){

super(props);

this.callPrint = this.callPrint.bind(this);

}

callPrint(){

this.props.functest()

}

render() {

return (

<TouchableHighlight onPress={this.callPrint} style= {styles.button}>

<Text>Navigate</Text>

</TouchableHighlight>

);

}

}

Either I get an error that says "this.props.functest" is not a function, or nothing happens at all. This seems like something that should be extremely simple. What can I do to fix this?

网友答案:

I pasted your code into a fresh react-native project and tested it on my Android phone.

  1. You need to use CamelCase for custom components, afaik: DrawerControl
  2. The DrawerControl class is missing openControlPanel() {}
  3. Main problem: calling console.log() prints to the iOS console. You need to run react-native log-ios in a terminal in order to view output, otherwise it'll appear as if nothing happend.

The error you mentioned about this.props.functest not being a function can occur in multiple ways, it should't happen with the code you posted here though, provided you make the changes I listed.

网友答案:

I think the problem is your props is already a function. So you do not need to call it like this.props.functest(). Just simply call like

<TouchableHighlight onPress={this.props.functest}}>
    <Text>Navigate</Text>
</TouchableHighlight>

I try to make a simple app via RNPlay base on your code and it works. https://rnplay.org/apps/2LJnbg

网友答案:

in your Class 1 change following.

<Home 
  openControlPanel={this.openControlPanel.bind(this)}
  functest={this._printtest()}>
</Home>

you need to call _printtest function

网友答案:

If you do not set props you will not be able to use it. props is just an argument for the constructor and is not an attribute of you instance meaning this.props is undefined. However you could set this.props = props in your constructor.

相关阅读:
Top