简体   繁体   中英

React - Child onClick event doesn't trigger when binding parameters

My problem is the following.

  • I have a "BookShelf" component which contains a "Book" list.
  • The parent (bookshelf) manage in its state a "selectedBook" property.
  • When clicking on one child (book), I would like to update its parent selectedBook property.
  • To achieve this, I use a function defined in the parent properties.
  • But this method is never trigerred (I tried with a console.log('something') but it never shows.

See my code below :

setSelectedBook(index) {
    this.setState({
        selectedBook: index
    })
},
getInitialState() {
    return {
        books: [],
        selectedBook: null
    }
},
componentDidMount() {
    let component = this
    $.ajax({
        url: 'data/books.json',
        success (data) {
            component.setState({
                books: data
            })
        },
        error (err) {
            console.log(err)
        }
    })
},
render() {
    let component = this
    var bookList = this.state.books.map(function(book, index) {
        let selectBook = component.setSelectedBook.bind(component, index)
        return (
             <Book onClick={selectBook} data={book} key={index} />
         )
    })
    return <div className="book-shelf">
        {bookList}
    </div>
}

Thanks in advance !

Here is a simple example for you. Also fiddle

You should pass your onClick event as a props to child component, once child component gets it, it will call a callback and pass an id as an agrument to the callback (like i have below).

class Book extends React.Component {
    constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(){
    this.props.click(this.props.id)
  }
    render(){
    return  <li onClick={this.handleClick}>{this.props.id} - {this.props.name}</li>
  }
}

class BookShelf extends React.Component{
    constructor(){
    super();
    this.onClick = this.onClick.bind(this)
  }
  onClick(id){
    console.log(id)
  }
  render(){
    return <ul> // of course you may use Array.map functions, it's just for example
      <Book click={this.onClick} id={1} name={'hello'}/>
      <Book click={this.onClick} id={2} name={'world'}/>
    </ul>
  }
}

React.render(<BookShelf />, document.getElementById('container'));

Also i suggest look at this article Communicate Between Components , it will be useful for you.

Thanks

select method return anonymous function as value.

<Book onClick={this.selectBook(index)} data={book} key={index} />

 selectBook (index){ return ((() => { console.log(" selectBook fired" ); component.setState({selectedBook:index}); }).bind(component,index)) }

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