[英]How do I get my checkbox values and option values to add up and enter the sum into my text area?
[英]How can I get my component to calculate the sum of checkbox values in React?
此應用程序呈現食物列表,旁邊帶有復選框。 我有一個組件,應該在檢查時計算和顯示復選框值的總和。 我無法顯示復選框中的值。
這是目前我所擁有的。
此文件呈現食物列表,每個食物旁邊都有復選框。
import React from "react";
import { Card, Accordion } from "react-bootstrap";
const Cards = props => {
return (
<Accordion defaultActiveKey="0">
<Card>
<Accordion.Toggle as={Card.Header} eventKey={`${props.key}`}>
<input
type="checkbox"
value={props.calories}
/>{" "}
{props && props.title + " : " + props.calories + "cal"}
</Accordion.Toggle>
<Accordion.Collapse eventKey={`${props.key}`}>
<Card.Body>
{" "}
{props.obj.nutrients &&
"fat: " + props.obj.nutrients["fat"]} ||{" "}
{props.obj.nutrients &&
"trans fats: " + props.obj.nutrients["transfat"]}
</Card.Body>
</Accordion.Collapse>
</Card>{" "}
</Accordion>
);
};
export default Cards;
我希望此組件與 Cards 組件中輸入框中的“props.calories”值進行求和。 這是我迄今為止嘗試過的。
import React from 'react';
import Cards from './card';
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked:false
};
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked() {
this.setState({isChecked: !this.state.isChecked});
}
render() {
var total;
if (this.state.isChecked) {
total += <Cards.input.value/>;
}
return (
<div>
<h1>Total: {total}</h1>
</div>
);
}
}
export default Calculator;
我是 React 的新手,任何幫助將不勝感激。 謝謝你。
很抱歉,上面給出的示例中有多個錯誤。 由於您是 React 的新手,因此 JSX 最初聽起來像是一個陌生的概念,這是可以預料的。
我已經重現了您正在尋找的場景:
https://codesandbox.io/s/react-example-uctkj
希望能幫助到你 !
如果您不理解示例中的某些內容,請隨時發表評論。
我不確定為什么要使用不同的組件來計算值。 您可以僅使用 Card 組件的狀態來計算。 此外<Cards.input.value/>;
似乎不對。 如果您在 props 中傳遞值而不是使用props. <your prop >
props. <your prop >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.