简体   繁体   中英

Use .bind(this) in style attribute

I have a simple function:

fullscreen2 () {
    console.log('test')
}

And I'm trying to pass the current element to it:

<div style={this.fullscreen2.bind(this)}>

The function does not seem to trigger. This works however:

<div style={this.fullscreen2()}>

First of all, it depends on whether you use React.createClass (which have auto-bind) or ES6 classes.

<div style={this.fullscreen2()}>

Call the function this.fullscreen2 and pass its return value to the style of this div tag.

<div style={this.fullscreen2.bind(this)}>

Bind the function's this object ( this.fullscreen2 ) to the current this (eg the instance class object). What is the return type of Function.bind ?

Well, this method returns a new function, so you pass to the style object a new function!

The fix would be:

<div style={this.fullscreen2.bind(this)()}>

But once again, you might not need to bind, refer to Shubham Khatri's answer for an example without bind.

Bind is useful only if you need to access: this.state , this.props or similar instance-specific attributes that might be lost due to the way you define your function.

To understand more how does this works (when my function lose the context, when it does not), look around how lexical scope works in JavaScript.

You do not need to bind the valye to the function, you ca directly pass it in the arguments like

 class App extends React.Component { function2 = (val, val2) => { console.log('in here', val, val2); if(val == '2') { return { backgroundColor: 'blue' } } else { return { backgroundColor: 'orange' } } } render() { return ( <div style={this.function2('2', '3')}>Hello World</div> ) } } ReactDOM.render(<App/>, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div> 

You can use this too:

class App extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.fullscreen2 = this.fullscreen2.bind(this);
  }

  fullscreen2 () {
    console.log('test')
  }

  render() {
    return(
      <div>
        <button onClick={this.fullscreen2}>fullscreen</button>
      </div>
    )
  }

}

export default App;

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