【问题标题】:add input field when button is clicked单击按钮时添加输入字段
【发布时间】:2016-05-31 05:01:50
【问题描述】:

我有一个用于添加配方的表格,其中有成分按钮。一个食谱可以有很多成分。单击该按钮时,用于添加成分的输入字段应出现在成分按钮下方。我试图做的是?

import Input from './Input.jsx';

export default class Sell extends Component {
    constructor()
    {
        super();
        this.state = {
          inputValues : {}
        }
        this.onHandleSubmit =this.onHandleSubmit.bind(this);
    }

    onChange( name, { target : { value } })
    {
         const inputValues = this.state.inputValues;
         inputValues[name] = value;
         this.setState({ inputValues })
    }

    onHandleSubmit()
    {
        console.log('clicked');
        const name = `ingrediant-${Object.keys(this.state.inputValues).length}`;
        let inputbox = <Input name={ name }
                              onChange={ this.onChange.bind(this, name )} />

    }

    onSubmit(event){
        event.preventDefault();
    }

    render() {
        return (
            <div className="row">
                <h2 className="flow-text text-center">Add Recipe</h2>
                <form onSubmit={this.onSubmit} className="col offset-s4 s4">
                  <div className="row">
                    <div className="input-field col s12">
                      <input ref="name" id="name" type="text" className="validate flow-text" />
                      <label htmlFor="name">Name of Recipe</label>
                    </div>
                  </div>
                    <div className="input-field col s12">
                        <a onClick={this.onHandleSubmit} className="waves-effect waves-light btn btn-block"><i className="material-icons right">add</i>Ingredients</a>
                    </div>
                  </div>
                  {this.state.inputValues}
                  <div className="row">
                    <button className="waves-effect waves-light btn btn-block">Submit</button>
                  </div>
                </form>
            </div>
        );
    }
}

单击按钮时如何为成分创建新的动态(新创建的输入框的引用不同)输入字段?

【问题讨论】:

  • @AvraamMavridis 发送到服务器。因为如果用户添加了 5 种成分,那么所有这 5 种成分应该有不同的 ref 发送到服务器。如果我错了,请纠正我?
  • 我没有看到它被使用过,你不要在任何地方做this.refs
  • 我还没有完成 onSubmit 任务,因为单击按钮时我无法添加成分字段。我在我的注册页面中使用了 ref,就像这样 let email = this.refs.email.value.trim();让密码 = this.refs.password.value.trim();让 confirmPassword = this.refs.confirmPassword.value.trim(); if(password === confirmPassword && password !== "" && confirmPassword !== ""){ let Info = { email:email, password:password }; Accounts.createUser(Info, (er) => { if(er){ ... }else { FlowRouter.go('/'); } }); }else{ .. }

标签: javascript reactjs ecmascript-6


【解决方案1】:

在您的情况下,我会将输入设为单独的组件,例如

class Input extends Component
{

    render()
    {
      const { name, onChange } = this.props;
      return(<div className="row">
                <div className="input-field col s12">
                  <input id={name} 
                         type="text" 
                         className="validate flow-text" 
                         onChange={ this.props.onChange } />
                  <label htmlFor={name}>Name of Recipe</label>
                </div>
         </div>)
    }

}

并从Sell 组件传递一个onChange 回调,Sell 组件将维护输入的值,并且当您想要将值发送到服务器时,您拥有它的状态。比如:

class Sell extends Component
{
    constructor()
    {
        super();
        this.state = {
          inputValues = {},
          inputs : []
        }
    }

    onChange( name, { target : { value } })
    {
         const inputValues = this.state.inputValues;
         inputValues[name] = value;
         this.setState({ inputValues })
    }

    onHandleSubmit()
    {
        const name = `incrediant-${this.state.inputs.length}`;
        let inputbox = <Input name={ name }
                              key={this.state.inputs.length}
                              onChange={ this.onChange.bind(this, name )} />

       const inputs = this.state.inputs;
       inputs.push( inputbox );
       this.setState( { inputs } );

    }

   ...
   ....

   render()
   {
       ...
       ...
       {
           this.state.inputs.map( i => i );
       }
   }

}

在这种情况下,您不必保留refs

【讨论】:

  • 点击一个成分按钮后,没有出现新的输入框。
  • 我收到此错误 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {}).
  • @milan 你必须渲染它,我没有将它添加到我的答案中更简短,你可以做类似this.state.inputs.push( &lt;Input /&gt;) 的事情,然后在你的渲染函数中使用map。喜欢{ this.state.inputs.map( i =&gt; i ) }
  • 是的,它奏效了。谢谢。您删除了 Object.keys()。我能知道原因吗?
  • 使用 Object.keys 名称未更新为新长度,但现在更新为新长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多