[英]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.