简体   繁体   English

如何在反应js中找到动态输入的总和

[英]How to find sum of dynamic inputs in react js

//this is api response { "message": "success", "code": 100, "data": { "inCourseCategories": [ { "_id": "62b842f09184bf2330e6f506", "course": "601a67e6db65fb15946e6b6f", "title": "test in 1 update", "__v": 0 }, { "_id": "62b8566d9184bf2330e6f6a6", "course": "601a67e6db65fb15946e6b6f", "title": "test 3update", "__v": 0 } ], "responseCode": 109 } } Below is my code: I need sum of the inputs, also the default values and sum must be 0 //这是 api 响应 { "message": "success", "code": 100, "data": { "inCourseCategories": [ { "_id": "62b842f09184bf2330e6f506", "course": "601a67e6db65fb15946e6b6f", "title “:“测试 1 更新”,“__v”:0 },{“_id”:“62b8566d9184bf2330e6f6a6”,“课程”:“601a67e6db65fb15946e6b6f”,“标题”:“测试 3update”,“__v”:0 }], "responseCode": 109 } } 下面是我的代码:我需要输入的总和,默认值和总和必须为 0

//html code //incoursedetails = response.data.inCourseCategories //html 代码 //incoursedetails = response.data.inCourseCategories

{incoursedetails && incoursedetails.map((item,index)=>
                    <div className='justify-btw mb-2'>
                      <p>{item.title}</p><input onChange={(e)=>handleInScoreChange(e,index)} [enter image description here][1] className='score-input form-control' type="text" name="" id="" />
                    </div>)}

<p className='fw-500'>Score Category</p><p className='text-black'>20</p>  //display sum


const handleInScoreChange = (e , index)=>{
 //what to do here, please help
}
  [1]: https://i.stack.imgur.com/jW1ys.png

You need to use state for this - rather two states: one for the sum, and one for the inputs as you change their values.您需要为此使用状态- 而不是两种状态:一种用于求和,另一种用于更改其值时的输入。 You'll also need to use the useEffect hook so that when the input object changes you can change the sum state.您还需要使用 useEffect 挂钩,以便在输入对象更改时可以更改sum状态。

Note: I've used a separate Field component but you may not need to do that - but it's the "React Way".注意:我使用了一个单独的Field组件,但您可能不需要这样做 - 但它是“React Way”。

 const { useEffect, useState } = React; function Example({ data }) { // Initalise your states. `sum` has an initial // value of zero, and your inputs state is an // empty object const [ sum, setSum ] = useState(0); const [ inputs, setInputs ] = useState({}); // When `getSum` is called get the values // of each property in the `inputs` state, `reduce` // them down, and then set the `sum` state function getSum() { const values = Object.values(inputs); const sum = values.reduce((acc, c) => acc + c, 0); setSum(sum); } // This gets called when any of the input values // change. It gets the name and value from the input, // and then updates the `inputs` state with that information function handleInput(e) { const { name, value } = e.target; setInputs({ ...inputs, [name]: +value }); } // When `inputs` changes call `getSum` useEffect(() => getSum(), [inputs]); // `map` over the data. Grab the id and title // from each object and then return a new Field // for each passing in the current input value, the // title, and the `handleInput` handler return ( <div> {data.map(obj => { const { id, title } = obj; return ( <Field key={id} type="number" title={title} value={inputs[id]} handleInput={handleInput} /> ); })} <div className="sum">Sum: {sum}</div> </div> ); } // `Field` simply builds up // a little fieldset with a title, and // an input function Field(props) { const { value, type, title, handleInput } = props; return ( <fieldset> <legend>{title}</legend> <input type={type} name={title} value={value} onChange={handleInput} /> </fieldset> ); } const data=[{_id:"62b842f09184bf2330e6f506",course:"601a67e6db65fb15946e6b6f",title:"test in 1 update",__v:0},{_id:"62b8566d9184bf2330e6f6a6",course:"601a67e6db65fb15946e6b6f",title:"test 3update",__v:0}]; ReactDOM.render( <Example data={data} />, document.getElementById('react') );
 fieldset { display: inline; padding: 0.5em; background-color: #efefef;} input { margin: 0.5em 0; padding: 0.2em 0; } legend { text-transform: uppercase; } .sum { font-size: 1.3em; text-transform: uppercase; margin-top: 1em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

Additional documentation附加文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM