【问题标题】:How to assign an id / className / refs to an input box and then call it in a variable using React?如何将 id / className / refs 分配给输入框,然后使用 React 在变量中调用它?
【发布时间】:2020-09-10 08:50:45
【问题描述】:
我是 React 初学者,我刚刚开始学习 React。这是我正在从事的第一个项目,它是一个费用跟踪器。我几乎完成了,但有一件事我无法理解:你如何在反应中使用 id 和 classNames?我曾尝试使用 refs 但这给了我一个错误。 我只是想给价格输入框分配一个id,然后在变量中调用它没有任何错误。有人可以帮我弄这个吗? 我的密码:
import React from 'react';
//import logo from './logo.svg';
import './App.css';
function App() {
var income = prompt("What is your income")
var incometxt = income
var price = React.findDOMNode(this.refs.price).value
var expenses = 0
function btnfunc() {
expenses = +price + +expenses
console.log(expenses, price)
}
return(
<>
<div>
<h1>Income:</h1><h1>{incometxt}</h1>
<h1>Expense:</h1><h1>{expenses}</h1>
</div>
<div>
<input type="number" placeholder="Expense price" ref="price"></input>
<button onClick={btnfunc}>Click me</button>
</div>
</>
)
}
export default App;
【问题讨论】:
标签:
javascript
html
reactjs
react-native
variables
【解决方案1】:
使用useState 钩子可以更好地实现您的目标:
import React, { useState } from "react";
//import logo from './logo.svg';
import "./App.css";
function App() {
var income = prompt("What is your income");
var incometxt = income;
const [price, setPrice] = useState(null);
var expenses = 0;
function btnfunc() {
expenses = +price + +expenses;
console.log(expenses, price);
}
return (
<>
<div>
<h1>Income:</h1>
<h1>{incometxt}</h1>
<h1>Expense:</h1>
<h1>{expenses}</h1>
</div>
<div>
<input type="number" placeholder="Expense price" value={price} onChange={(e) => setPrice(e.target.value)}/>
<button onClick={btnfunc}>Click me</button>
</div>
</>
);
}
export default App;
【解决方案2】:
这并不能完全回答问题,但我建议使用这样的状态
import React, {useState} from 'react';
//import logo from './logo.svg';
import './App.css';
function App() {
const [price, setPrice] = useState()
var income = prompt("What is your income")
var incometxt = income
var expenses = 0
function btnfunc() {
expenses = +price + +expenses
console.log(expenses, price)
}
return(
<input
type="number"
placeholder="Expense price"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
)
}
export default App;