如何在响应

时间:2017-01-10 05:41:23

标签: reactjs react-redux



class BankForm extends Component {
   constructor() {
     super();
     this.onSubmit = this.onSubmit.bind(this);
   }

   onSubmit(e) {
     e.preventDefault();
     console.log(e.target.price.value);
   }

   render() {
      return (
        <AddForm onSubmit={this.onSubmit} />
      );
   }
}

function AddForm(props) {
   return (
      <div>
        <form onSubmit={props.onSubmit}>
           <input type="number" name="price" />
           <input type="number" name="price" />
           <button type="submit">Submit</button>
        </form>
      </div>
    );
}
&#13;
&#13;
&#13;

如何将两个输入名称导入到react

中的数组中

请在console.log中修改我的代码(e.target.price.value);

我试过了:

的console.log(e.target.price.value [0]); X

的console.log(e.target.price [0]。价值); X

如果只有一个价格,此代码将很有效。

帮帮我!!! :C

3 个答案:

答案 0 :(得分:0)

根据react docs,您应该做的是为您的输入值设置支持状态字段。在反应中,这被称为受控输入。在更改每个输入时,您将输入值存储到状态。由于您需要一组价格,因此您需要将一些状态变量设置为数组,然后在输入的每次更改时,将新值存储在该状态数组中。在渲染时,您需要再次设置输入值,以便它可见。

class BankForm extends React.Component {
   constructor() {
     super();
     this.onSubmit = this.onSubmit.bind(this);
     this.state = {
       price: [
         21,
         55
       ]
     };
   }

   onSubmit(e) {
     e.preventDefault();
     console.log(this.state.price);
   }

   onPriceChange(index, e) {

     var prices = this.state.price.slice();

     prices[index] = e.target.value;

     this.setState({
       price: prices
     });
   }

   render() {
      return (
        <div>
        <form onSubmit={this.onSubmit}>
           <input type="number"  value={this.state.price[0]} onChange={this.onPriceChange.bind(this, 0)} />
           <input type="number"  value={this.state.price[1]} onChange={this.onPriceChange.bind(this, 1)} />
           <button type="submit">Submit</button>
        </form>
      </div>
      );
   }
}

在这个例子中,我通过预先设置数组值来默认文本框值,但你可以通过使用像这样的空数组来改变它

this.state = {
           price: []
         };

每个输入都将其onChange事件连接到onPriceChange函数。该函数只是通过复制price数组来更新状态,然后使用传入的索引设置一个新值。

onPriceChange(index, e) {

         var prices = this.state.price.slice();

         prices[index] = e.target.value;

         this.setState({
           price: prices
         });
       }

最后onsubmit只是将当前状态打印到控制台

onSubmit(e) {
         e.preventDefault();
         console.log(this.state.price);
       }

我有一个可以玩的example on webpackbin here。我知道,如果你有大型表格,这似乎很多工作,但有一个我喜欢的库,这使得这个非常简单,称为formsy

Formsy通过使用mixins包装所有这些工作,并允许您构建可重用的表单组件,如文本框,组合等。将它们放在一个formy表单组件中,神奇地在onsubmit事件中,你有一个很好的模型可以使用你的代码可能看起来像这样。

import Formsy from 'formsy-react';

  const MyAppForm = React.createClass({
    getInitialState() {
      return {
        canSubmit: false
      }
    },
    enableButton() {
      this.setState({
        canSubmit: true
      });
    },
    disableButton() {
      this.setState({
        canSubmit: false
      });
    },
    submit(model) {
      someDep.saveEmail(model.email);
    },
    render() {
      return (
        <Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}>
          <MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/>
          <button type="submit" disabled={!this.state.canSubmit}>Submit</button>
        </Formsy.Form>
      );
    }
  });

在您的表单提交处理程序formy中将为您提供根据您的输入值生成的模型。在封面下,formy正在完成为每种输入类型设置支持状态字段的所有工作,因此您不必这样做。

答案 1 :(得分:0)

在您的情况下,事件的target<form>,输入是其子项,因此为了访问其值,您需要获取子项。最简单的解决方法是onSubmit方法:

   onSubmit(e) {
     e.preventDefault();
     for (let i = 0; i < e.target.children.length; i++) {
            if (e.target.children[i].name === 'price') {
                console.log('value: ', e.target.children[i].value)
            }
     }
   }

JSFiddle with your code

答案 2 :(得分:0)

试试这个

<!-- index.html -->
<div id="app"></app>

/* In index.jsx */
import React, {Component} from 'react';
import ReactDom from 'react-dom';

class BankForm extends Component {
  constructor() {
    super();
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(e) {
    e.preventDefault();

    // This will go through every item with name 'price' and get for you
    e.target.querySelectorAll('[name="price"]').forEach((e, i) => {
      console.log('Value of', i, 'th Item is:',  e.value);
    });

  }

  render() {
    return (
        <AddForm onSubmit={this.onSubmit}/>
    );
  }
}

function AddForm(props) {
  return (
      <div>
        <form onSubmit={props.onSubmit}>
          <input type="number" name="price"/>
          <input type="number" name="price"/>
          <button type="submit">Submit</button>
        </form>
      </div>
  );
}

ReactDom.render(<BankForm />, document.getElementById('app'));

输出

Value of 0 th Item is: 2
Value of 1 th Item is: 3