I don't understand why the input field is not refreshing.
(我不明白为什么输入字段没有刷新。)
The main idea is
(主要思想是)
There is a list containing some names and when the user clicks it, the card component below
(有一个包含一些名称的列表,当用户单击它时,下面的卡组件)
is rendered with 2 things the name and an input field ( the value is set to the name )
(用2东西的名字和一个输入字段(值设置为名字)呈现。)
below explains what the code does...
(下面解释了代码的作用...)
The state contains all the names and by clicking the add button more names are added to the list ( which is the state ).
(该状态包含所有名称,通过单击添加按钮,更多名称将添加到列表中(状态)。)
There is another state which keeps the track of the current person.
(还有另一种状态可以跟踪当前人。)
Every name is rendered as a button (DOM_persons).
(每个名称都呈现为一个按钮(DOM_persons)。)
On clicking the person the currentPerson state changes. (单击人员后,currentPerson状态将更改。)
import React , {useState} from 'react';
import './App.css';
import Card from './Card';
function App() {
const [state,changeState] = useState(['Jerry'])
const [currentPerson,changeCurrnetPerson] = useState(state[0])
function addItem(){
const names = ['Karren','Jesus','Wilfredo','Samuel','Chi','Kellye','Kazuko','Mae','Olevia','Ines']
const newState = [...state]
newState.push(names[Math.floor(Math.random()*names.length)])
changeState(newState)
}
function changePerson(i){
changeCurrnetPerson(state[i])
}
const DOM_persons = state.map((p,i) => <button key={i} onClick={()=>{changePerson(i)}} >{p}</button> )
return (
<div className="App">
{DOM_persons}
<Card name={currentPerson}/>
<button onClick={addItem}>add</button>
</div>
);
}
export default App;
this is the card component
(这是卡组件)
Card.js
(Card.js)
import React ,{useState} from 'react'
export default function Card({name}){
const [value,changeValue] = useState(name)
function handleChange(e){
changeValue(e.target.value)
}
return(
<div>
<h4>{name}</h4>
<input value={value} onChange={handleChange}/>
</div>
)
}
ask by yasir jafar translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…