任务是将输入的每个字符传递给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>
答案 0 :(得分:1)
您必须使用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>
答案 1 :(得分:0)
向input
元素添加onChange
处理程序。注意:处理程序传递了event
,因此您需要从事件目标中获取值。在这里,我使用了destructuring。
function App() {
function handleExchange(e) {
const { target: { value } } = e;
console.log(value)
}
return (
<input
className="input-r"
placeholder="Type here"
onChange={handleExchange}
/>
);
}
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>