-1

I am new on react I tried to execute this function in react

export default class App extends Component{
render(){
function SSS(t)
{
  this.t=t;
 return this;
}
console.log(SSS(1).t);
}return(
<h1>H</h1>
)}
}

but it still gives me that error

TypeError: Cannot set property 't' of undefined

I read about "this" in MDN they mentioned the reason of this error is how to call the function
it works perfectly on js pure.
could you help me with that,please ?
thnx!

HUS.97
  • 7
  • 1
  • 5

2 Answers2

0

SSS function call should assign t variable onto its execution context, e.g., if you call it in within window object, the variable can be accessed from there, window.t // 1. Provided you are in 'use strict' mode., you will get
TypeError: Cannot set property 't' of undefined

If you want to bind custom context to SSS, you should either use call/apply/bind, examples:

SSS.call({}, 1)
SSS.apply({}, [1])
SSS.bind({})(1);

or constructor call:

new SSS(1);
Dodge
  • 41
  • 2
0

Welcome to StackOverflow.

You're using "this" in a function-in-function, "this" is not defined there.

What you want is put SSS(t) outside of render, as a class method.

Like this:

export default class App extends Component{
  SSS(t)
  {
    this.t=t;
    return this;
  }

  render(){
    console.log(this.SSS(1).t);
    return(
      <h1>H</h1>
    );
  }
}

Also, not that doing this.t = t is dangerous in React. You should probably use this.state.t and this.setState() instead. Check this for more info :

xurei
  • 1,057
  • 8
  • 22