如何将输入框输入的值作为父类reactJS中的组件

时间:2022-08-22 19:39:04

I have created InputField and button as separate component and make use of in the two js files incomeFields and Emifields. Then the two Js file as a component called in mail file called HomeLoanEmiCalculator. Then another file success file to calculate based on the input provided. on click of next button the value will be save in one object and we can retreive the entered value inside the success file to calculate the EMI values. I refer the site below https://www.online.citibank.co.in/products-services/loans/pop-up/home-loan-eligibility-calculator.htm as we have to create in ReactJS. Below code not working properly. Even am using ref i cannot able to access the fieldvalues

我已经创建了InputField和button作为单独的组件,并在两个js文件中使用了incomeFields和Emifields。然后将两个Js文件作为一个名为HomeLoanEmiCalculator的邮件文件中调用的组件。然后根据提供的输入计算另一个文件成功文件。点击下一个按钮,该值将保存在一个对象中,我们可以在成功文件中检索输入的值以计算EMI值。我参考https://www.online.citibank.co.in/products-services/loans/pop-up/home-loan-eligibility-calculator.htm以下的网站,因为我们必须在ReactJS中创建。下面的代码不能正常工作。即使我使用ref我也无法访问fieldvalues

var React = require('react');
var InputField = React.createClass({
  getInitialState: function(){
      return{
        value: this.props.value || '',
    };
  },
  setValue: function (event) {
    this.setState({
      value: event.currentTarget.value
    });
    setDefaultValue =   this.props.fieldValues+"."+this.props.stateId;
  },
  render: function() {
    return (<div>
                    <div>
                    <input className="inputText" id={this.props.stateId} type="text" 
                    ref={this.props.stateId} onChange={this.props.setValue} defaultValue={this.props.setDefaultValue}/>
                            </div>);
  }

});
module.exports = InputField;

var React = require('react')
var InputField = require('./InputField')
var IncomeFields = React.createClass({
nextStep: function(e) {     
e.preventDefault();     
var data = {            
monthlyIncome : this.refs.monthlyIncome.getDOMNode().value,         
rentalIncome  : this.refs.rentalIncome.getDOMNode().value,          
otherIncome   : this.refs.otherIncome.getDOMNode().value        
}       
this.props.saveValues(data);
        this.props.nextStep();

},
render: function() {   

return (<div>
            <h2>Please enter your income details</h2>
                                    <ul className="inputList">
                                        <li className="width25 hlec">
                                            <InputField name="Gross Monthly Income"
                                                stateId="monthlyIncome"
                                                metrics= "INR"
                                                required="true"
                                                setDefaultValue={this.props.fieldValues.monthlyIncome}
                                                imgPath="images/icons/icon_rupee.png"/>
                                        </li>
                                        <li className="width25 hlec">
                                            <InputField name="Rental Income"
                                                stateId="rentalIncome"
                                                metrics= "INR"
                                                setDefaultValue={this.props.fieldValues.rentalIncome}
                                                imgPath="images/icons/icon_house.png"/>
                                        </li>
                                        <li className="width25 hlec last">
                                            <InputField name="Other Income"
                                                stateId="otherIncome"
                                                metrics= "INR"
                                                setDefaultValue={this.props.fieldValues.otherIncome}
                                                imgPath="images/icons/icon_cashBundle.png"/>
                                        </li>
                                    </ul>
        </div>

    )
  }
})

module.exports = IncomeFields

var React = require('react')
var InputField = require('./InputField')
var EmiFields = React.createClass({

    nextStep: function(e) {
        e.preventDefault();
        var data = {
            mortageLoan : this.refs.mortageLoan.getDOMNode().value,
            persoanlLoan  : this.refs.persoanlLoan.getDOMNode().value,
            creditLoan   : this.refs.creditLoan.getDOMNode().value,
            autoLoan : this.refs.autoLoan.getDOMNode().value,
            outstandingCCAmount : this.refs.outstandingCCAmount.getDOMNode().value,
            interestRate : this.refs.interestRate.getDOMNode().value
        }
        this.props.saveValues(data);
        this.props.nextStep();
},
render: function() {   

return (<div>
            <h2>Please enter your income details</h2>
                                    <ul className="inputList">
                                        <li className="width25 hlec">
                                            <InputField name="Any other Mortgage Loan"
                                                stateId="mortageLoan"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_house.png"/>
                                </li>
                                <li className="width25 hlec">
                                            <InputField name="Personal Loan"
                                                stateId="personalLoan"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_user.png"/>
                                </li>
                                <li className="width25 hlec">
                                            <InputField name="Loan on Credit Card"
                                                stateId="creditLoan"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_card.png"/>
                                </li>
                                <li className="width25 hlec last">
                                            <InputField name="Auto Loan"
                                                stateId="autoLoan"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_car.png"/>
                                </li>
                            </ul>
                            <ul className="inputList part2">
                                <li className="width25 hlec">
                                            <InputField name="Outstanding Amount on Credit Card"
                                                stateId="outstandingCCAmount"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_rupee.png"/>
                                </li>
                                <li className="width25 hlec last">
                                            <InputField name="Auto Loan"
                                                stateId="otherLoan"
                                                metrics= "INR"
                                                imgPath="images/icons/icon_rupee.png"/>
                                </li>
                            </ul>
        </div>

    )
  }
})

module.exports = EmiFields

var React = require('react');

var EmiCalculations = require('./store/EmiCalculator');

var aboutLoanStyle = {
    width: '235px', 
    marginRight: '10px'
};

var loanAvail = null;
var homeValue = null;
var monthlyEMI = null;

var Success = React.createClass({

  render: function() {
    return (
                <div> {this.calculate}
                    <div className="section1 outputSection">
                            <ul className="outputRack">
                                <li className="c2">
                                    <div className="outputLabel">
                                        <strong>Maximum Home Loan available to you</strong>
                                    </div>
                                    <div className="outputValue last" id="loanAvail" ref="loanAvail" defaultValue={this.props.fieldValues.loanAvail}>{EmiCalculations.getLoanAvail(this.props.fieldValues)}</div>
                                </li>
                                <li className="c2 last">
                                    <div className="outputLabel">
                                        <strong>Value of Home you can purchase</strong>
                                    </div>
                                    <div className="outputValue last" id="homevalue" ref="homeValue" defaultValue={this.props.fieldValues.homeValue}>{EmiCalculations.getHomeValue(this.props.fieldValues)}</div>
                                </li>
                            </ul>
                            <ul className="outputRack rack2">
                                <li className="c2">
                                    <div className="outputLabel">
                                        <strong>Your Monthly EMI</strong>
                                    </div>
                                    <div className="outputValue last" id="monthlyEMI" ref="monthlyEMI" defaultValue={this.props.fieldValues.monthlyEMI}>{EmiCalculations.getMonthlyEMI(this.props.fieldValues)}</div>
                                </li>
                            </ul>
                        </div>
                        </div>

    )
  }
})

module.exports = Success

var React = require('react')
var IncomeFields = require('./IncomeFields')
var aboutLoanStyle = {
    width: '235px',
    marginRight: '10px'
};

var Navigation = React.createClass({
   getInitialState: function() {
        return {
                  nextCount: 1
        }
    },
    nextStep: function(e) {

        e.preventDefault();
         var cnt = ++this.state.nextCount
     this.props.nextStep(cnt);
     this.setState({nextCount: cnt});
     console.log(IncomeFields.props.fieldValues);
    },
    render: function() {
    return (<div className="inputButtonSection">
            <div className="right step1">
                <button className="blueBtn" style={aboutLoanStyle}>KNOW MORE ABOUT HOME LOANS</button>
                {this.props.nextBtnVisibility ? <button key={this.state.showEmiField} className="blueBtn nextBtn" style={this.props.btnStyle} onClick={this.nextStep}>{this.props.nextStepLabel}</button> : null}
                {this.props.resetBtnVisibility ? <button className="greyBtn reset first" onClick={this.resetValues}>RESET</button> : null }
            </div>
              </div>
    )
  }
})

module.exports = Navigation
var React         = require('react')
var IncomeFields = require('./IncomeFields')
var EmiFields  = require('./EmiFields')
var Success       = require('./Success')
var assign        = require('object-assign')
var Navigation = require('./Navigation')

var fieldValues = {
    principalAmount : 100000,
    monthlyIncome: null,
  rentalIncome : null,
  otherIncome  : null,
    mortageLoan : null,
    persoanlLoan : null,
    creditLoan : null,
    autoLoan : null,
    outstandingCCAmount : null,
    otherLoan : null,
    downPayment : null,
    loanTenure : null,
    loanAvail: null,
    homeValue: null,
    monthlyEMI: null
};

var HomeLoanEMICalculator = React.createClass({
    getInitialState: function() {
     return {
                 nextStepCount: 1,
                 nextStepLabel: "NEXT",
                 showEmiField: false,
                 showTenureFields: false,
                 showOutput: false,
                 nextBtnVisibility: true,
                 resetBtnVisibility: false,
                 btnStyle : {
                   marginRight: '10px'
                 }
     }
 },
  saveValues: function(field_value) {
    return function() {
      fieldValues = assign({}, fieldValues, field_value)
    }.bind(this)()
  },
    nextStep: function(count) {
    //this.setState({nextStepCount: count});
        this.showNext(count, true);
  },
    showNext: function(c, bool) {
            if(c===2) {
                this.setState({resetBtnVisibility : bool});
                this.setState({showEmiField: bool});
            } else if(c===3) {
                this.setState({showTenureFields: bool});
                this.setState({nextStepLabel: "CALCULATE"});
                btnStyles = {
                    width: '110px',
                    marginRight: '10px'
                }
                this.setState({btnStyle: btnStyles});
            } else if(c===4) {
                this.setState({showOutput: bool});
                this.setState({nextBtnVisibility: false});
            }
    },
  render: function() {
    return (
      <div className="calculatorWrapper">
                    <IncomeFields fieldValues={fieldValues}
                                                    nextStep={Navigation.nextStep}
                                                    saveValues={this.saveValues}/>
                    {this.state.showEmiField ? <EmiFields fieldValues={fieldValues}
                                                    nextStep={Navigation.nextStep}
                                                    saveValues={this.saveValues}/>: null}
                {this.state.showOutput ? <Success fieldValues={fieldValues}/> : null}
                    <Navigation nextBtnVisibility={this.state.nextBtnVisibility} resetBtnVisibility={this.state.resetBtnVisibility} btnStyle={this.state.btnStyle} nextStepLabel={this.state.nextStepLabel} nextStep={this.nextStep}/>
      </div>
    )
  }
})
module.exports = HomeLoanEMICalculator

var React        = require('react')
var ReactDOM        = require('react-dom')
var HomeLoanEMICalculator = require('./components/HomeLoanEMICalculator')

window.onload = function() {
  ReactDOM.render(
    <HomeLoanEMICalculator />,
    document.getElementById('emi-calc-form')
  )
}

Please help me to do this. pls thanks in advance

请帮我这样做。请提前感谢

1 个解决方案

#1


0  

There are a few problems with what you are trying to do:

你要做的事情有一些问题:

If you read the documentation on refs: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

如果您阅读refs上的文档:https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

You will see that you need to assign a ref attribute on the component you want to get the DOM value for.

您将看到需要在要获取DOM值的组件上分配ref属性。

this.refs.monthlyIncome.getDOMNode().value

only works if you do something like:

仅在您执行以下操作时才有效:

<input className="inputText" type="text" ref="monthlyIncome" />

One way of tackling this is to have the fields be properties in a state, and based on whether those states are set, trigger your form to move into it's next state. You probabl

解决这个问题的一种方法是让字段成为状态中的属性,并根据是否设置了这些状态,触发表单进入下一个状态。你可能

The code may resemble something like below. You still need to implement functions so that onChange will update the state. You can easily replace input with InputField if input field takes the value via props, and the onChange function comes back up to change the state.

代码可能类似于下面的内容。您仍然需要实现函数,以便onChange将更新状态。如果输入字段通过props获取值,则可以使用InputField轻松替换输入,并且onChange函数会重新启动以更改状态。

 var InputField = React.createClass({
  getInitialState: function(){
    return {mortgageLoan: null, principalAmount: null};
  },
  renderFirstForm: function() {
        return (
          <div>Mortgage Loan: <input className="inputText" value={this.state.mortgageLoan} /></div>
        )
      },
      firstFormComplete: function() {
        return (this.state.mortgageLoan != null);
      }
      renderSecondForm: function() {
        return (
      <div>Principal Amount: <input className="inputText" value={this.state.principalAmount} onChange={} /></div>
    )
  }

})

#1


0  

There are a few problems with what you are trying to do:

你要做的事情有一些问题:

If you read the documentation on refs: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

如果您阅读refs上的文档:https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

You will see that you need to assign a ref attribute on the component you want to get the DOM value for.

您将看到需要在要获取DOM值的组件上分配ref属性。

this.refs.monthlyIncome.getDOMNode().value

only works if you do something like:

仅在您执行以下操作时才有效:

<input className="inputText" type="text" ref="monthlyIncome" />

One way of tackling this is to have the fields be properties in a state, and based on whether those states are set, trigger your form to move into it's next state. You probabl

解决这个问题的一种方法是让字段成为状态中的属性,并根据是否设置了这些状态,触发表单进入下一个状态。你可能

The code may resemble something like below. You still need to implement functions so that onChange will update the state. You can easily replace input with InputField if input field takes the value via props, and the onChange function comes back up to change the state.

代码可能类似于下面的内容。您仍然需要实现函数,以便onChange将更新状态。如果输入字段通过props获取值,则可以使用InputField轻松替换输入,并且onChange函数会重新启动以更改状态。

 var InputField = React.createClass({
  getInitialState: function(){
    return {mortgageLoan: null, principalAmount: null};
  },
  renderFirstForm: function() {
        return (
          <div>Mortgage Loan: <input className="inputText" value={this.state.mortgageLoan} /></div>
        )
      },
      firstFormComplete: function() {
        return (this.state.mortgageLoan != null);
      }
      renderSecondForm: function() {
        return (
      <div>Principal Amount: <input className="inputText" value={this.state.principalAmount} onChange={} /></div>
    )
  }

})