[英]How to change state value with prompt in React Js?
當我在提示中寫 smth 時,我希望它改變 Hayko 的值......這意味着,當你在瀏覽器中打開它時,它顯示 cragravorox,在此之后我想要提示改變 Hayko 的那個值......
const Count = () => {
const [Hayko, setHayko] = useState('cragoravorox')
return(
<>
<div>{Hayko}</div>
<button onClick={() => {prompt(('enter my name') )}}> Change me </button>
</>
)
}
export default Count
在這里找到了 Dacre Denny 的一個例子
const enteredName = prompt('Please enter your name') // Integrating this with your existing react component can be done in a number of ways - one approach might be as follows: /* Definition of handleClick in component */ handleClick = (event) => { /* call prompt() with custom message to get user input from alert-like dialog */ const enteredName = prompt('Please enter your name') /* update state of this component with data provided by user. store data in 'enteredName' state field. calling setState triggers a render of this component meaning the enteredName value will be visible via the updated render() function below */ this.setState({ enteredName : enteredName }) } render: function() { return ( <div> {/* For demonstration purposes, this is how you can render data previously entered by the user */ } <p>Previously entered user name: { this.state.enteredName }</p> <input type="text" onChange={ this.handleChange } /> <input type="button" value="Alert the text input" onClick={this.handleClick} /> </div> ); } });
將提示值設置為變量
const promptValue = prompt(('enter my name')
然后在sethayko(promptValue)
鈎子 onClick 中使用它,例如
<button onClick={() => sethayko(promptValue)}> Change me </button>
你可以簡單地做:
const Count = () => {
const [Hayko, setHayko] = useState('foo');
return (
<>
<div>{Hayko}</div>
<button onClick={() => setHayko(prompt('enter my name'))}>Change me</button>
</>
);
}
不評論使用 prompt 的美學:)
你在那里。 您只是缺少需要使用prompt
調用返回的值 - 這將是用戶輸入的值 - 然后將狀態設置為該值。 以下是如何以最小的改動做到這一點:
const Count = () => {
const [Hayko, setHayko] = useState('cragoravorox')
return(
<>
<div>{Hayko}</div>
<button onClick={() => setHayko(prompt('enter my name'))}> Change me </button>
</>
)
}
export default Count
但這不是最容易閱讀的,因此您可能需要一個名為handleClick
類的單獨函數,以便更清楚地了解正在發生的事情:
const Count = () => {
const [Hayko, setHayko] = useState('cragoravorox')
const handleClick = () => {
const newHayko = prompt(('enter my name'))
setHayko(newHayko)
}
return(
<>
<div>{Hayko}</div>
<button onClick={handleClick}}> Change me </button>
</>
)
}
export default Count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.