简体   繁体   中英

How can we add ''+'' two different value in react jsx

I am taking value in input but in result i want to add "+" 10% in the result ie if a person inputs 1000 and the 10% of 1000 is 100 and the total result will be 1100. I am using "+" but it is concatenating the value istead of adding

function app() {
  const [price, setPrice] = useState(0);
  return (
    <div>
      <label>Price</label>
      <input
        type="number"
        value={price}
        onChange={e => setPrice(e.target.value)}
      />
      <div>{price + (10 / 100) * price}</div>
    </div>
  );
}

How can i add these two values

Use Number to avoid setting price as a String:

function app(){
const [price,setPrice]=useState(0);
return(
<div>
  <label>Price</label>
  <input
  type='number'
  value={price}
  onChange={(e)=> setPrice(Number(e.target.value))}
 </div>
  {price + (10/100)*price}
/>
}

Beware of NaN though.

All you have to do is to add a plus sign + before e.target.value to convert it to a number:

function app() {
  const [price, setPrice] = useState(0);
  return (
    <div>
      <label>Price</label>
      <input type="number" value={price} onChange={(e) => setPrice(+e.target.value)} />
      {price + (10 / 100) * price}
    </div>
  );
}

You can use parseInt for convert string to number in JavaScript. Problem in your script you are adding 2 values string and number.

function app() {
  const [price, setPrice] = useState(0);
  return (
    <div>
      <label>Price</label>
      <input
        type="number"
        value={price}
        onChange={e => setPrice(e.target.value)}
      />
      <div>{(parseInt(price) + (10 / 100)) * parseInt(price)}</div>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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