React不向组件发送值

时间:2018-03-12 12:39:52

标签: javascript reactjs react-proptypes

我是新手,为了训练,我正在做一个简单的书籍排名项目。目前,用户输入他或她想要投票的书。如果该输入为空,则返回错误消息,但如果不是,则返回成功消息。

这是输入:

<form onSubmit={this.onSubmit}>
     <input ref={input => this.input = input} /><br />
     <button type="submit">Tell us</button>
</form>

此处onSubmit代码绑定到输入onSubmit

onSubmit(event) {
    event.preventDefault();
    if(this.input.value===''){
        console.log('========ENTRADA INVÁLIDA=========')
        this.setState({
            messageSucess: false,
            openDialog: true
        });
        this.input.focus();
    }        
    else{
        console.log('The user voted:')
        console.log(this.input.value)
        this.setState({
            bestBook: this.input.value,
            messageSucess: true,                                
            openDialog: true
        });
        this.input.value = '';
        this.input.focus();
    }
}

我发送messageSucess变量的组件只会检查它是真还是假。如果是,则返回成功消息。如果不是,则出现错误消息。代码:

class DialogModal extends React.Component {
    render() {
        //Return's nothing if it's show property is false.
        if (!this.props.show) {
            return null;
        }

        //Return message of sucess or error.
        return (
            <div>
                {this.props.messageSucess ? (
                     <div className="Modal">
                         <div className="Modal-Body sucess-message">
                             <br/>Thanks vor voting {this.props.children}, we will tell everybody about this sweet piece of violence.
                         </div>
                     </div>
                 ) : (
                     <div className="Modal">
                         <div className="Modal-Body error-message">
                             <br />Please, enter the book you want to vote for.
                         </div>
                     </div>
                 )}
            </div>
        );
    }
}

DialogModal.propTypes = {
    onClose: PropTypes.func.isRequired,
    show: PropTypes.bool,
    messageSucess: PropTypes.bool,
    children: PropTypes.node
};

export default DialogModal;

但由于某种原因,messageSucess没有进入DialogModal组件。为了确保我在代码的几个部分中尝试console.log它的值,就像在ModalDialog中返回之前,或者之后    主类中的this.input.focus(),但它总是未定义的。我一直关注conditional rendering page of react,但到目前为止一无所获。

**更新:**正如评论中所述,这里是我添加DialogModal组件的地方:

            <DialogModal 
                show={this.state.openDialog}
                onClose={this.modalOpened}>
            </DialogModal>

onClose事件只会将show属性更改为反向。我检查了是否正确导入了所有内容。

1 个答案:

答案 0 :(得分:3)

您需要将messageSucess属性传递给Dialog,如

<DialogModal 
  show={this.state.openDialog}
  onClose={this.modalOpened}
  messageSucess={this.state.messageSucess}
/>
相关问题