2017-06-13 88 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