如何使用React.JS正确验证输入值? [英] How to properly validate input values with React.JS?

查看:92
本文介绍了如何使用React.JS正确验证输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表格。所有组件和状态都保存在Page组件中。有2个显示标题和3个输入字段。第一个输入应该是文本,第二个和第三个输入应该是整数。当用户输入错误类型的数据时,我希望在输入字段旁边弹出一条错误消息。我的问题与React.JS中的最佳做法有关。

I have a simple form. All of the components and state are held in the Page component. There are 2 display headers and 3 input fields. The first input is supposed to be text, and the second and third are supposed to be ints. When the user inputs the wrong type of data, I want to have an error message pop up next to the input field. My questions relate to best practices in React.JS

谁决定该值有效?我想输入字段的唯一作用是将值引导回保持状态的组件,这是否意味着只有Page可以确定某个值是否有效?

Who decides that the value is in valid? I suppose that the only job of the input field is to direct the value back to component holding the state, so does this mean that only Page can determine if a value is valid?

然后我应该怎么出现弹出窗口? Page必须触发一个新的布尔状态元素,该元素将通过perp传递,告诉Adaptive_Input显示错误消息吗?

How should I then have the pop up appear? Should Page have to trigger a new boolean state element that will be passed through perp that will tell Adaptive_Input to reveal the error message?

JSFiddle

JS:

/**
 * @jsx React.DOM
 */
var Adaptive_Input = React.createClass({ 
    handle_change: function(){
        var new_text = this.refs.input.getDOMNode().value;
        this.props.on_Input_Change(new_text);
    },
    render: function(){
        return (
                <div className='adaptive_placeholder_input_container'>
                    <input 
                        className="adaptive_input"
                        type="text" 
                        required="required" 
                        onChange= {this.handle_change}
                        ref="input"
                    ></input>
                    <label
                        className="adaptive_placeholder"
                        alt={this.props.initial}
                        placeholder={this.props.focused}
                    ></label>
                </div>              
                );
    }
});

var Form = React.createClass({
    render: function(){
        return (
                <form>
                    <Adaptive_Input
                        initial={'Name Input'}
                        focused={'Name Input'}
                        on_Input_Change={this.props.handle_text_input}
                    />
                    <Adaptive_Input
                        initial={'Value 1'}
                        focused={'Value 1'}
                        on_Input_Change={this.props.handle_value_1_input}
                    />
                    <Adaptive_Input
                        initial={'Value 2'}
                        focused={'Value 2'}
                        on_Input_Change={this.props.handle_value_2_input}
                    />
                </form>
                );
    }
});

var Page = React.createClass({
    getInitialState: function(){
        return {
            Name : "No Name",
            Value_1 : '0',
            Value_2 : '0',
            Display_Value: '0'
        };
    },
    handle_text_input: function(new_text){
        this.setState({
                Name: new_text
            });
    },
    handle_value_1_input: function(new_value){
        console.log("===");
        var updated_display = parseInt(new_value) + parseInt(this.state.Value_2);
        updated_display = updated_display.toString();
        this.setState({
                Display_Value: updated_display 
            });
    },
    handle_value_2_input: function(new_value){
        var updated_display = parseInt(this.state.Value_1) + parseInt(new_value);
        updated_display = updated_display.toString();
        this.setState({
                Display_Value: updated_display
            });
    },
    render: function(){
        return(
                <div>
                    <h2>{this.state.Name}</h2>
                    <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
                    <Form
                        handle_text_input={this.handle_text_input}
                        handle_value_1_input = {this.handle_value_1_input}
                        handle_value_2_input = {this.handle_value_2_input}
                    />
                </div>
        );
    }
});

React.renderComponent(<Page />, document.body);


推荐答案

首先,这是我要做的一个例子请注意以下内容: http://jsbin.com/rixido/2/edit

First, here is an example of what I'll mention below: http://jsbin.com/rixido/2/edit

如何使用React.JS正确验证输入值?

How to properly validate input values with React.JS?

但是你想要。 React用于呈现数据模型。数据模型应该知道什么是有效的。您可以使用Backbone模型,JSON数据或任何您想要表示数据及其错误状态的内容。

However you want. React is for rendering a data model. The data model should know what is valid or not. You can use Backbone models, JSON data, or anything you want to represent the data and it's error state.

更具体地说:

React通常与您的数据无关。这是为了渲染和处理事件。

React is generally agnostic towards your data. It's for rendering and dealing with events.

遵循的规则是:


  1. 元素可以改变他们的状态。

  2. 他们不能改变道具。

  3. 他们可以调用一个可以改变顶级道具的回调。

如何决定某事物应该是道具还是国家?考虑一下:除了文本字段之外,你的应用程序的任何部分都想知道输入的值是坏的吗?如果不是,请将其设为状态。如果是,则它应该是道具。

How to decide if something should be a prop or a state? Consider this: would ANY part of your app other than the text field want to know that the value entered is bad? If no, make it a state. If yes, it should be a prop.

例如,如果您想要一个单独的视图来呈现此页面上有2个错误。然后你的错误必须为顶级数据模型所知。

For example, if you wanted a separate view to render "You have 2 errors on this page." then your error would have to be known to a toplevel data model.

该错误应该在哪里?

如果你的应用程序正在渲染Backbone模型(例如,模型本身将具有您可以使用的validate()方法和validateError属性。您可以渲染其他可以执行相同操作的智能对象。 React还表示尽量将道具保持在最低限度并生成其余数据。所以,如果您有一个验证器(例如 https://github.com/flatiron/revalidator ),那么您的验证可能会逐渐减少组件可以通过匹配验证检查道具,看看它是否有效。

Where should that error live?
If your app was rendering Backbone models (for example), the model itself would have a validate() method and validateError property you could use. You could render other smart objects that could do the same. React also says try to keep props to a minimum and generate the rest of the data. so if you had a validator (e.g. https://github.com/flatiron/revalidator) then your validations could trickle down and any component could check props with it's matching validation to see if it's valid.

这在很大程度上取决于你。

It's largely up to you.

(我个人使用Backbone模型并在React中呈现它们。我有一个顶级错误警告,我会在任何地方出现错误时显示,描述错误。)

(I am personally using Backbone models and rendering them in React. I have a toplevel error alert that I show if there is an error anywhere, describing the error.)

这篇关于如何使用React.JS正确验证输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆