score:272
es6 react.component
doesn't auto bind methods to itself. you need to bind them yourself in constructor
. like this:
constructor (props){
super(props);
this.state = {
loopactive: false,
shuffleactive: false,
};
this.ontoggleloop = this.ontoggleloop.bind(this);
}
score:0
if you call your created method in the lifecycle methods like componentdidmount... then you can only use the this.ontoggleloop = this.ontoogleloop.bind(this)
and the fat arrow function ontoggleloop = (event) => {...}
.
the normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.
score:0
in my case, for a stateless component that received the ref with forwardref, i had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd
from this (onclick doesn't have access to the equivalent of 'this')
const com = forwardref((props, ref) => {
return <input ref={ref} onclick={() => {console.log(ref.current} } />
})
to this (it works)
const usecombinedrefs = (...refs) => {
const targetref = react.useref()
useeffect(() => {
refs.foreach(ref => {
if (!ref) return
if (typeof ref === 'function') ref(targetref.current)
else ref.current = targetref.current
})
}, [refs])
return targetref
}
const com = forwardref((props, ref) => {
const innerref = useref()
const combinedref = usecombinedrefs(ref, innerref)
return <input ref={combinedref } onclick={() => {console.log(combinedref .current} } />
})
score:0
you can rewrite how your ontoggleloop method is called from your render() method.
render() {
var shuffleclassname = this.state.toggleactive ? "player-control-icon active" : "player-control-icon"
return (
<div classname="player-controls">
<fontawesome
classname="player-control-icon"
name='refresh'
onclick={(event) => this.ontoggleloop(event)}
spin={this.state.loopactive}
/>
</div>
);
}
the react documentation shows this pattern in making calls to functions from expressions in attributes.
score:1
if you are using babel, you bind 'this' using es7 bind operator https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding
export default class signuppage extends react.component {
constructor(props) {
super(props);
}
handlesubmit(e) {
e.preventdefault();
const data = {
email: this.refs.email.value,
}
}
render() {
const {errors} = this.props;
return (
<div classname="view-container registrations new">
<main>
<form id="sign_up_form" onsubmit={::this.handlesubmit}>
<div classname="field">
<input ref="email" id="user_email" type="email" placeholder="email" />
</div>
<div classname="field">
<input ref="password" id="user_password" type="new-password" placeholder="password" />
</div>
<button type="submit">sign up</button>
</form>
</main>
</div>
)
}
}
score:2
in my case this was the solution = () => {}
methodname = (params) => {
//your code here with this.something
}
score:3
you should notice that this
depends on how function is invoked
ie: when a function is called as a method of an object, its this
is set to the object the method is called on.
this
is accessible in jsx context as your component object, so you can call your desired method inline as this
method.
if you just pass reference to function/method, it seems that react will invoke it as independent function.
onclick={this.ontoggleloop} // here you just passing reference, react will invoke it as independent function and this will be undefined
onclick={()=>this.ontoggleloop()} // here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
score:12
i ran into a similar bind in a render function and ended up passing the context of this
in the following way:
{somelist.map(function(listitem) {
// your code
}, this)}
i've also used:
{somelist.map((listitem, index) =>
<div onclick={this.somefunction.bind(this, listitem)} />
)}
score:34
write your function this way:
ontoggleloop = (event) => {
this.setstate({loopactive: !this.state.loopactive})
this.props.ontoggleloop()
}
the binding for the keyword this is the same outside and inside the fat arrow function. this is different than functions declared with function, which can bind this to another object upon invocation. maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.dosomethingwith(x)).
score:108
there are a couple of ways.
one is to add
this.ontoggleloop = this.ontoggleloop.bind(this);
in the constructor.
another is arrow functions
ontoggleloop = (event) => {...}
.
and then there is onclick={this.ontoggleloop.bind(this)}
.
Source: stackoverflow.com
Related Query
- Using arrow functions inside React component does not transfer over parent context (which exists). this remains undefined in arrow function
- React setState inside of a function this is undefined
- React - this is undefined when binding function to component
- React TypeError: " this is undefined ", function inside function call not working
- React: "this" is undefined inside a component function
- React Hooks Error: Hooks can only be called inside the body of a function component
- React Warning: Cannot update a component from inside the function body of a different component
- Function inside functional component in React hooks - Performance
- React - stateless component, function inside or outside component
- Jest -- Mock a function called inside a React Component
- Mock React useRef or a function inside a functional component with enzyme and jest?
- React: 'this.state' is undefined inside a component function
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- React Native : Access Component state inside a static function
- React + Antd + Rollup Component Library "Error: Invalid hook call. Hooks can only be called inside of the body of a function component"
- React Hooks can only be called inside the body of a function component
- use of variable inside render function of react component
- React 17.0.1: Invalid hook call. Hooks can only be called inside of the body of a function component
- Receiving error - Hooks can only be called inside of the body of a function component when implementing React Spring basic example
- How to use React Context inside function of Class component
- export function inside react component or access state in same file outside of component
- react - conditional rendering inside component return function
- this.props shows as undefined in an arrow function within React Component
- I got an error for using React.useRef inside a react function component
- this.state is undefined inside function - React JS
- React Hooks Mobx: invalid hook call. Hooks can only be called inside of the body of a function component
- React Hooks - function inside function component passed as prop can't access state
- How does React Context work by using a function inside of a component
- how to set react parent component state by a async function and then pass this state to child as props?
- React router v4.2.2: using a string instead of function inside component prop of Route results in error
More Query from same tag
- Tracker.autorun not working inside componentDidMount of react
- Private Route getting called dozens of times in React
- How to toggle active class of tabs in React?
- How do I get data on a specific id from firestore in react?
- unable to find component.jsx in react app
- a React-Redux Action Update Multiple Reducers
- Formik handleReset is going through validation
- is there a way to wait till a function runs before an axis patch call
- React Hooks: useQuery data are gone after page refresh
- Use setInterval without increasing memory consuming
- app.auth is not a function error in firebase react
- Why use `useTable` over `ReactTable` when using react-table
- React, Printing the state of an array and updating state on button press
- Not able to Initialize Firebase APP inside script module in HTML
- How can I use Google Analytics code in React JS app?
- Load More Pagination using Prisma, Urql & React?
- react native firebase how to make query synchronous
- define .env file except default env file in react app
- How to invoke a React-router client side redirect to a new url in JS without using <Link>
- Get sum from the nested array of objects
- want to redirect to page after the action is dispatched in useEffect
- Why is passing function argument to React.useState and the return function will return stale value
- How to log data after calling function
- React filter payload arrays
- What is the intention of using React's useCallback hook in place of useEffect?
- React Flux dispatcher vs Node.js EventEmitter - scalable?
- Multiple Redux states in a single component - Typescript, React, Redux
- How to check if the array of object is null using react and javascript?
- Array is shuffling in React JS
- Uncaught TypeError: Cannot read property 'history' of undefined !! React router