【问题标题】:how to bind data in reactjs formreactjs表单中如何绑定数据
【发布时间】:2018-02-02 08:05:52
【问题描述】:

我已经开始研究 reactjs 技术,我对这项技术完全陌生。我想将数据与表单中的下拉列表绑定,在下拉项目选择中,我想提供其他表单字段。在这里,我正在创建表单来为社团成员生成账单,我想填写社团成员名称以便在下拉时绑定文本字段上的下拉框和账单更改。有时我遇到问题说“TypeError:节点为空”。而且我不明白如何将数据绑定到字段。

这是我的逻辑,请检查并让我知道我在这里缺少什么

 constructor(props, fdb) {
        super(props);

        this.state = {
            bill_nm: '',
            bill_eml: '',
            bill_total: '',
            bill_id: '',
            inputs:[],
            userInput:[]
        };
        this.userState = {
            user_id:'',
            email:'',
            first_name:'',
            last_name:''
        };
        this.chargeState ={
            charge_id:'',
            charge_title:'',
            charge_type:'',
            charge_amt:''
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmitFirebase = this.handleSubmitFirebase.bind(this);
        this.sendCallback = this.sendCallback.bind(this);
        this.appendInput = this.appendInput.bind(this);
        this.getInitialState = this.getInitialState.bind(this);
        this.appendUserInput = this.appendUserInput.bind(this);
        this.usercharge = [];

        const rootRef = DbConfig.database().ref();
        const post = rootRef.child('billing').orderByKey();
        const users = rootRef.child('users').orderByKey();
        const bill_charges = rootRef.child('billing_charges').orderByKey();

    }

    componentDidMount() {

             this.users.once('value', snap => {
            snap.forEach(child => {
                this.userState = {
                    user_id: child.key,
                    email: child.val().email,
                    first_name: child.val().first_name,
                    last_name: child.val().last_name
                };

            });

        });

        this.bill_charges.once('value', snap => {
            snap.forEach(child => {
                this.chargeState = {
                    chrage_key:child.key,
                    charge_id: child.charge_id,
                    charge_title: child.val().charge_title,
                    charge_type: child.val().charge_type,
                    charge_amt: child.val().charge_amt
                };
                this.usercharge = this.chargeState;
               //console.log( this.usercharge);
            });
        });

        }

           handleChange(event) {
        this.setState({ value: event.target.value });
    }


   getInitialState() {
        return {inputs:[]};
    }
    appendUserInput() {
        //e.preventDefault();

        // DbConfig.database().ref().child('users').orderByKey().once('value', snap => {
        //     snap.forEach(child => {
        //         this.userState = {
        //             user_id: child.key,
        //             email: child.val().email,
        //             first_name: child.val().first_name,
        //             last_name: child.val().last_name
        //         };
        //     });
        // });
        var newInput1 = this.state.userInput.length;
       // var newInput = this.userState.length;
        console.log('len1='+newInput1);
       // console.log('len'+newInput);
        this.setState({ userInput: this.state.userInput.concat(newInput1)});

    }
    appendInput(e) {
        e.preventDefault();
        var newInput = this.state.inputs.length;
            console.log('newinput'+newInput);
        this.setState({ inputs: this.state.inputs.concat(newInput)},function(){
            return;
        });
        console.log('input concate'+this.state.inputs);
    }

      render() {
        return (
            <div className="content">
                <NavBar></NavBar>
                <div className="row">
                    <div className="col-md-10">
                        <div className="card">
                            <div className="card-header card-header-icon" data-background-color="rose">
                                <i className="material-icons">receipt</i>
                            </div>
                            <div className="card-content">
                                <h4 className="card-title">Add Bill</h4>
                                <form onSubmit={this.handleSubmitFirebase}>
                                    <div className="form-group label-floating is-empty">
                                        <label className="control-label">Person Name</label>

                                        <div className="room-main">
                                        <div className="online-est">                                         
                                                <a href="javascript:void(0);" onClick={this.appendUserInput} className="rednew-btn"><i className="fa fa-plus-circle"></i> Add user</a>
                                            <select className="room-form">
                                           {this.state.userInput.map(function(item){
                                               console.log('i'+item);
                                                return (
                                                          <option ref={item}>{item}</option> 
                                                       )
                                           })}
                                           </select>
                                        </div>
                                    </div>
                                        <span className="material-input"></span></div>
                                    <div className="form-group label-floating is-empty">
                                    <label className="control-label">Person Name</label>
                                        <div className="room-main">
                                        <div className="online-est"> 
                                                <a href="javascript:void(0);" onClick={this.appendInput} className="rednew-btn"><i className="fa fa-plus-circle"></i> Add charge</a>
                                            <select>
                                           {this.state.inputs.map(function(item){
                                                return (
                                                            <option ref={item}>{item}</option>
                                                       )
                                           })}
                                           </select>
                                        </div>
                                    </div>
                                    <span className="material-input"></span></div>
                                    <div className="form-group label-floating is-empty">
                                            <label className="control-label">status</label>
                                            <select>
                                                <option value="Unpaid">Unpaid</option>
                                                <option value="Paid">Paid</option>
                                            </select>
                                        <span className="material-input"></span></div>
                                    <div className="form-group label-floating is-empty">
                                            <label className="control-label">total</label>
                                            <input type="text" className="form-control" ref={el => this.billtotal = el} onChange={this.handleChange} />
                                        <span className="material-input"></span></div>
                                    <div className="form-group label-floating is-empty">
                                            <label className="control-label">Bill period</label>
                                            <input type="date" className="form-control" ref={el => this.billto = el} onChange={this.handleChange} />
                                            <input type="date" className="form-control" ref={el => this.billfrom = el} onChange={this.handleChange} />
                                        <span className="material-input"></span></div>
                                    <div className="form-group label-floating is-empty">
                                        <span className="material-input"></span></div>
                                    <button type="submit" className="btn btn-fill btn-rose">Submit</button>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        )
    }

【问题讨论】:

  • 错误信息什么时候出现?是在渲染期间吗?或者表单是否正确呈现,但是当您在表单中执行某些操作时会出现错误消息?如果是在表单中做某事的时候,请同时包含 onChange 函数代码
  • 错误信息是'TypeError: node is null'并且在渲染过程中显示。
  • 表单未呈现此错误出现在页面加载时它会阻止在页面上显示另一个组件它给我空白页。

标签: javascript reactjs firebase firebase-realtime-database


【解决方案1】:

您可以使用构造函数,在构造函数中初始化状态并在构造函数中绑定方法,而不是使用获取初始状态。

constructor(props) {
  super(props);
  this.state = {
    listVisible: false
  };
 this.select = this.select.bind(this)
 this.show = this.show.bind(this)
 this.hide = this.hide.bind(this)
 this.renderListItems = this.renderListItems.bind(this)
}

然后,当您在渲染方法中调用 select 时,您应该只能说...

<div onClick={this.select(item)}>
  <span>{item.name}</span>
</div> 

虽然您需要在 react 中添加一个键来跟踪列表,但请将第一行更改为 &lt;div key={i} onClick={this.select(item)}&gt;。您可以单独阅读密钥https://reactjs.org/docs/lists-and-keys.html#keys

【讨论】:

  • 您也可以在没有构造函数的情况下执行此操作,并使用箭头函数绑定它,但使用 ES7。我认为理解和使用这种方法是最好的,就目前而言,这是 Airbnb 风格指南推荐的方式,也是我们所拥有的最接近行业标准的方式。
  • 我也做了同样的事情,但它说 "this.props.selected.name" ,this.props.list is undefied
  • 你将不得不给我更多。这是哪里说的?什么触发了错误?
  • 使用 react 开发者工具或 console.log 检查您的列表是否按预期传递,如果它说列表未定义。
  • 这个错误在页面加载时也遇到了我,并且这个仅在我的控制台窗口中显示
【解决方案2】:
<div className="post">
  <h3>{this.state.bill_nm}</h3>
  <h2>{this.state.bill_eml}</h2>
  <p>{this.state.bill_total}</p>
</div>

上述这些状态值从未定义过。您需要在初始状态下定义它们,或者在调用它们之前设置它们。

在渲染中输入的 onChange 处理程序中,您正在调用 this.handleChange,但它们也没有被定义。

<input type="text" className="form-control" ref={el => this.pnm = el} onChange={this.handleChange} />

我认为这个代码示例不完整。

为了回答标题问题,本文解释了您在 react https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 中绑定 this 的选项

【讨论】:

    【解决方案3】:

    作为替代方案,您可以尝试 Redux Form https://redux-form.com,它将为您完成大部分工作

    【讨论】:

    • 跳到 redux 作为不了解状态基础并将其绑定到 react 的解决方案是一个糟糕的主意。
    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多