gpt4 book ai didi

javascript - 将输入的值传递给handleMethod

转载 作者:行者123 更新时间:2023-12-02 22:33:53 24 4
gpt4 key购买 nike

任务是将输入的每个字符传递给handleExchange方法。在此方法中,将处理输入的值。

如何将输入标记传递给 handleExchange 方法的参数?

function App() {

function handleExchange(value) {
console.log(value)
}

return (
<input className = "input-r" placeholder = "Type here" />
)


}

ReactDOM.render(<App /> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

我尝试这样做:

function App() {
function handleExchange(value) {
console.log(value);
}

return (
<div>
<input className="input-r" placeholder="Type here" onKeyPress={handleExchange(this.value)} />
{/*or*/}
{/* onKeyPress={handleExchange(event) */}
</div>
)

}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

最佳答案

您必须使用onChange事件并从event.target获取值。

你有例子:

function App() {
function handleExchange(e) {
console.log(e.target.value);
}

return (
<div>
<input className="input-r" placeholder="Type here" onChange={handleExchange} />
{/*or*/}
{/* onKeyPress={handleExchange(event) */}
</div>
)

}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - 将输入的值传递给handleMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com