React - 绑定参数时不触发Child onClick事件
问题描述:
我的问题如下。React - 绑定参数时不触发Child onClick事件
- 我有一个包含“Book”列表的“BookShelf”组件。
- 父(书架)在其状态下管理“selectedBook”属性。
- 当点击一个孩子(书)我想更新其父母selected书财产。
- 为了达到这个目的,我使用了在父属性中定义的函数。
- 但这种方法不会trigerred(我试过用的console.log( '东西'),但它绝不会显示
见下面我的代码:提前
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>
}
谢谢!
答
这是给你一个简单的例子。此外fiddle
你应该与你擦肩而过onClick
事件作为子组件的道具,一旦子组件获取它,它将调用一个回调函数并传递一个id作为对回调的补充(就像我下面的那样)。
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'));
此外,我建议看看这个article通信的组件之间,这将是对你有用。
谢谢
答
我希望这将有助于
试试这个way.selected方法返回匿名函数。
<Book onClick={this.selectBook(index)} data={book} key={index} />
selectBook (index){
\t return ((() => {
\t \t \t console.log(" selectBook fired");
\t \t \t component.setState({selectedBook:index});
\t \t \t }).bind(component,index))
\t
}
你'Book'成分如何触发'onClick'?您需要在'Book'组件中明确触发'props.onClick()' – Maxx
您能否粘贴'Book'组件的代码? –
我可能错过了一些东西。只有通过在书籍声明中添加onClick才能触发onClick? – OhmWang