1 回答
TA贡献1817条经验 获得超14个赞
您混淆了设置器功能。单击时,调用setInput('')
以清除输入,并将内容setString(input)
设置<h1>
为当前输入字符串:
function App() {
const [string, setString] = React.useState("")
const [input, setInput] = React.useState("")
function handleInput(event){
setInput(event.target.value)
}
function handleClick(){
setInput('')
setString(input)
}
return (
<div>
<input value={input} onChange={handleInput} />
<button onClick={handleClick}>Click</button>
<h1>your name: {string}</h1>
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
或者,更好的是,使用nameinstead of string,代码的意图会更清晰:
function App() {
const [input, setInput] = React.useState("")
const [name, setName] = React.useState("")
function handleInput(event){
setInput(event.target.value)
}
function handleClick(){
setInput('')
setName(input)
}
return (
<div>
<input value={input} onChange={handleInput} />
<button onClick={handleClick}>Click</button>
<h1>your name: {name}</h1>
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
添加回答
举报