2017-06-13 94 views
0

我有父組件TodoItem和兩個子組件:EditTodoItem和ShowTodoItem。我使用狀態版來切換這些兒童組件。如果是,則顯示EditTodoItem。 當版本爲false時,ShowTodoItem正在渲染。當我們點擊ShowTodoItem時,版本應該成爲true。但是這個代碼不工作:React onClick不起作用

import React from 'react' 
 
import PropTypes from 'prop-types' 
 
import ShowTodoItem from './TodoItem/ShowTodoItem' 
 
import EditTodoItem from './TodoItem/EditTodoItem' 
 

 
export default class TodoItem extends React.Component { 
 
    constructor(props) { 
 
     super(props); 
 
     this.handleOnTodoClick = this.handleOnTodoClick.bind(this); 
 
     this.handleOnEnterPress = this.handleOnEnterPress.bind(this); 
 
     this.state = { edition: false }; 
 
    } 
 

 
    handleOnTodoClick() { 
 
     console.log('edit'); 
 
     this.setState({ edition: true }); 
 
    } 
 

 
    handleOnEnterPress() { 
 
     this.setState({ edition: false }); 
 
    } 
 

 
    render() { 
 
     if (this.state.edition) { 
 
      return (
 
       <EditTodoItem item={this.props.item} onTodoChange={this.props.onTodoChange} onEnterPress={this.handleOnEnterPress} /> 
 
      ); 
 
     } 
 
     return (
 
      <ShowTodoItem onClick={this.handleOnTodoClick} item={this.props.item} onRemoveTodoClick={this.props.onRemoveTodoClick} /> 
 
     ); 
 
    } 
 
}

我在瀏覽器控制檯沒有錯誤,但我也沒有執行console.log(「編輯」)的結果;

回答

4

onClick不會觸發自定義組件,它只會觸發從jsx創建的dom節點。當您將onClick傳遞給自定義組件時,它會作爲道具傳入。請確保您的ShowItemTodo中的代碼具有如下所示的行:

return (
    <button onClick={this.props.onClick}>click me</button> 
) 
+0

謝謝,它的工作原理! – Olga