[英]React - rendering information in JSX
I am building a tip calculator.我正在构建一个小费计算器。 I need to render the result of the formula calculation in the div element.我需要在 div 元素中呈现公式计算的结果。 It works if insert formula directly into div, but I believe I have to use useState in this case.如果将公式直接插入 div,它会起作用,但我相信在这种情况下我必须使用 useState。 Here is the code I use.这是我使用的代码。 Could you please suggest how to fix it?你能建议如何解决它吗? thanks.谢谢。
import React, { useState } from 'react';
import './Calculation.css';
import Card from './UI/Card';
const Calculation = (props) => {
const [tipPP, setTipPP]=useState('0');
const [totalPP, setTotalPP] = useState('0');
const calcHandler =()=>{
setTipPP(((props.bill * props.tip) / props.people)/100);
setTotalPP(props.bill/props.people + tipPP)
}
return (
<Card className='calcCard' onChange = {calcHandler}>
<div className='calcTip' >Tip amount<span className='tipTotal' >${tipPP}</span></div>
<div className='calcTotal'>Total<span>${totalPP}</span></div>
<Card className='resetBtn'>Reset</Card>
</Card>
)
};
export default Calculation;
How about :怎么样 :
import React, { useState, useEffect } from 'react';
import './Calculation.css';
import Card from './UI/Card';
const Calculation = (props) => {
const [tipPP, setTipPP]=useState('0');
const [totalPP, setTotalPP] = useState('0');
const calcHandler =(e)=>{
e.preventDefault();
setTipPP(((props.bill * props.tip) / props.people)/100);
setTotalPP(props.bill/props.people + tipPP)
}
useEffect(() => {
console.log("tipPP changed!");
}, [tipPP]);
return (
<Card className='calcCard' onChange = {(e) => calcHandler()}>
<div className='calcTip' >Tip amount<span className='tipTotal' >${tipPP}</span></div>
<div className='calcTotal'>Total<span>${totalPP}</span></div>
<Card className='resetBtn'>Reset</Card>
</Card>
)
};
export default Calculation;
useEffect will re-render the component when the value of tipPP changes. useEffect 会在 tipPP 的值改变时重新渲染组件。 Please try this.请试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.