简体   繁体   中英

TypeError: this.props is not a function on handleCHange event

I browsed the answer to many questions here on this subject, and I think I doing everything I should but somehow it does not work.

Here is the isolated part of code throwing the error:

import React from 'react';
import Switchbookmarks from './switch';

class App extends React.Component {
  test(str){
    console.log(str)
  }
  render(){
  return (
    
    <div className="App">
      <Switchbookmarks>test={this.test.bind(this)}</Switchbookmarks>
    </div>
  );
}
}

export default App;

and switch.js file:

import React, { Component } from 'react'
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';

class Switchbookmarks extends Component{
  constructor(props) {
    super(props);
    this.state ={
      checkedA:false
    }
    this.handleChange = this.handleChange.bind(this)
  }
handleChange(event) {
    this.setState({ [event.target.name]: event.target.checked });
    if (event.target.checked) {
      this.props.test(event.target.checked);
    }
  };
  render (){
    return(
    <div style={{marginLeft: '65%', position: 'fixed'}}>
      <FormControlLabel
        control={<Switch checked={this.state.checkedA} onChange={this.handleChange} name="checkedA" />}
        label="Zakładki"
      />
      </div>
    )};
}
export default Switchbookmarks

I want to control other sibling component visibility based on the switch value. When the handleCHange is invoked it throws an error

TypeError: this.props.test is not a function.

What am I doing wrong here or is there any other method to accomplish this?

<Switchbookmarks>test={this.test.bind(this)}</Switchbookmarks>

Do you see the closed > ? It could be an possible issue.

<Switchbookmarks test={this.test.bind(this)}</Switchbookmarks>

I'm pretty confident you cannot bind the way you did. You should either bind in the construction and pass the props as "this.test" or simply change the test function to arrow function, and the test props EDIT: I don't even think you need to bind anything. simply pass the test as props.

test = (str) => {
    console.log(str)
  }
.....
<Switchbookmarks test={this.test}></Switchbookmarks>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM