P
P
PlasterTom2018-02-16 14:46:03
React
PlasterTom, 2018-02-16 14:46:03

What will happen with ES6?

Vorpos on this code. How to write in onDelete = this.props.onNoteDelete through ES6 so that the context is not lost?

render() {
    let onNoteDelete = this.props.onNoteDelete; 
    return(
    <div className="notes-grid" ref="grid">
            {this.props.notes.map(note => {
             return (
                <Note 
                key={note.id} 
                color={note.color}
                onDelete={onNoteDelete.bind(null, note)}> // и эта строка
                {note.text} 
                </Note>);   
            })
            }
    </div>
    )
 }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-16
@PlasterTom

You can do this:
In the component from which you pass the handler, define it as an inline arrow class function :

class Parent {
  onNoteDelete = note => {
    // some stuff
  };
}

Such functions do not lose context. Or, you can bind the handler in the constructor, as advised above. render
method :
render() {
  const { notes, onNoteDelete } = this.props; 
  
  return(
    <div className="notes-grid" ref="grid">
      {notes.map(note => (
        <Note 
          key={note.id} 
          color={note.color}
          onDelete={() => onNoteDelete(note)}
        >
          {note.text} 
        </Note>
       ))}
    </div>
  )
}

For values ​​that are not overridden, it's better to use const rather than let . This way other programmers will immediately see that the value is not overridden and as a result your code will be more readable.

R
Roman Aleksandrovich, 2018-02-16
@RomReed

render() {
    let onNoteDelete = this.props.onNoteDelete; 
    return(
    <div className="notes-grid" ref="grid">
            {this.props.notes.map(note => {
             return (
                <Note 
                key={note.id} 
                color={note.color}
                onDelete={()=>onNoteDelete.bind(null, note)}> // и эта строка
                {note.text} 
                </Note>);   
            })
            }
    </div>
    )
 }

or
constructor(props){
super(props)
this.onNoteDelete=this.onNoteDelete.bind(this)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question